Why do we need GROUP BY with AGGREGATE FUNCTIONS?

后端 未结 4 1109
旧时难觅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:38

    It might be easier if you think of GROUP BY as "for each" for the sake of explanation. The query below:

    SELECT empid, SUM (MonthlySalary) 
    FROM Employee
    GROUP BY EmpID
    

    is saying:

    "Give me the sum of MonthlySalary's for each empid"

    So if your table looked like this:

    +-----+------------+
    |empid|MontlySalary|
    +-----+------------+
    |1    |200         |
    +-----+------------+
    |2    |300         |
    +-----+------------+
    

    result:

    +-+---+
    |1|200|
    +-+---+
    |2|300|
    +-+---+
    

    Sum wouldn't appear to do anything because the sum of one number is that number. On the other hand if it looked like this:

    +-----+------------+
    |empid|MontlySalary|
    +-----+------------+
    |1    |200         |
    +-----+------------+
    |1    |300         |
    +-----+------------+
    |2    |300         |
    +-----+------------+
    

    result:

    +-+---+
    |1|500|
    +-+---+
    |2|300|
    +-+---+
    

    Then it would because there are two empid 1's to sum together. Not sure if this explanation helps or not, but I hope it makes things a little clearer.

提交回复
热议问题