Why do we need GROUP BY with AGGREGATE FUNCTIONS?

后端 未结 4 1099
旧时难觅i
旧时难觅i 2020-11-30 09:51

I saw an example where there was a list (table) of employees with their respective monthly salaries. I did a sum of the salaries and saw the exact same table in the ouptput

4条回答
  •  眼角桃花
    2020-11-30 10:18

    The sad thing is that there is one database that supports the syntax you are suggesting:

    SELECT EmployeeID, SUM (MonthlySalary) 
    FROM Employee
    

    However, MySQL does not do what you expect. It returns the overall sum of the MonthlySalary for everyone, and one arbitrary EmployeeId. Alas.

    Your question is about SQL syntax. The answer is that is how SQL has been defined, and it is not going to change. Determining the aggregation fields from the SELECT clause is not unreasonable, but it is not how this language is defined.

    I do, however, have some sympathy for the question. Many people learning SQL think of "grouping" as something done in the context of sorting the rows. Something like "sort the cities in the US and group them by state in the output". Makes sense. But "group by" in SQL really means "summarize by" not "keep together".

提交回复
热议问题