Why can't you mix Aggregate values and Non-Aggregate values in a single SELECT?

后端 未结 6 1978
我寻月下人不归
我寻月下人不归 2020-11-29 07:04

I know that if you have one aggregate function in a SELECT statement, then all the other values in the statement must be either aggregate functions, or listed in a GROUP BY

6条回答
  •  野性不改
    2020-11-29 07:12

    Think about it this way: when you call COUNT without grouping, it "collapses" the table to a single group making it impossible to access the individual items within a group in a select clause.

    You can still get your result using a subquery or a cross join:

        SELECT p1.Name, COUNT(p2.Name) AS Surname FROM People p1 CROSS JOIN People p2 GROUP BY p1.Name
    
        SELECT Name, (SELECT COUNT(Name) FROM People) AS Surname FROM People
    

提交回复
热议问题