Why do I need to explicitly specify all columns in a SQL “GROUP BY” clause - why not “GROUP BY *”?

后端 未结 3 2051
情话喂你
情话喂你 2020-12-05 15:12

This has always bothered me - why does the GROUP BY clause in a SQL statement require that I include all non-aggregate columns? These columns should be included by default -

3条回答
  •  我在风中等你
    2020-12-05 16:12

    The only logical reason I can think of to keep the GROUP BY clause as it is that you can include fields that are NOT included in your selection column in your grouping.

    For example.

    Select column1, SUM(column2) AS sum
     FROM table1
     GROUP BY column1, column3
    

    Even though column3 is not represented elsewhere in the query, you can still group the results by it's value. (Of course once you have done that, you cannot tell from the result why the records were grouped as they were.)

    It does seem like a simple shortcut for the overwhelmingly most common scenario (grouping by each of the non-aggregate columns) would be a simple yet effective tool for speeding up coding.

    Perhaps "GROUP BY *"

    Since it is already pretty common in SQL tools to allow references to the columns by result column number (ie. GROUP BY 1,2,3, etc.) It would seem simpler still to be able to allow the user to automatically include all the non-aggregate fields in one keystroke.

提交回复
热议问题