Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate function in SQL Server

Tags:

sql

sql-server

I'm getting really frustrated about SQL Server. I'm just trying to join 3 tables, very simple and easily done in mysql. But in SQL Server it keeps telling me to contain tbl_department.deptname in an aggregate function. But what aggregate function could I possibly use in a simple string?

SELECT      
    COUNT(tblStudent_Department.student_id) AS Expr2, 
    tbl_department.deptname AS Expr1
FROM          
    tblStudent_Department 
LEFT OUTER JOIN
    tbl_department ON tblStudent_Department.deptcode = tbl_department.deptcode 
LEFT OUTER JOIN
    tblStudent ON tblStudent_Department.student_id = tblStudent.studentid
GROUP BY 
    tblStudent_Department.deptcode

Please help.

like image 812
Wern Ancheta Avatar asked Aug 14 '26 05:08

Wern Ancheta


1 Answers

The database doesn't know that if you group on deptcode, you're implicitly grouping on deptname. You must tell SQL Server this by adding the column to the group by:

GROUP BY tblStudent_Department.deptcode, tbl_department.deptname

MySQL is special in that it basically picks a random row if you don't specify an aggregate. This can be misleading and lead to wrong results. As in many other things, MySQL has the more pragmatic solution, and SQL Server the more correct one.

like image 97
Andomar Avatar answered Aug 16 '26 20:08

Andomar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!