What do comma-separated integers in a GROUP BY statement accomplish?

主宰稳场 提交于 2019-12-12 10:53:45

问题


I have a query like this:

SELECT col1, col2, col3, col4, col5, SUM(col6) AS total
FROM table_name
WHERE col1 < 99999
GROUP BY 1,2,3,4,5

What does the GROUP BY statement actually accomplish here? The query does not work properly without the comma-separated integers.


回答1:


It is equivalent to writing:

SELECT col1, col2, col3, col4, col5, SUM(col6) AS total
  FROM table_name
 WHERE col1 < 99999
 GROUP BY col1, col2, col3, col4, col5

The numbers are the values/columns in the select-list expressed by ordinal position in the list, starting with 1.

The numbers used to mandatory; then the ability to use the expressions in the select-list was added. The expressions can get unwieldy, and not all DBMS allow you to use 'display labels' or 'column aliases' from the select-list in the GROUP BY clause, so occasionally using the column numbers is helpful.

In your example, it would be better to use the names - they are simple. And, in general, use names rather than numbers whenever you can.




回答2:


My guess is that your database product allows for referencing columns in the Group By by position as opposed to only by column name (i.e., 1 for the first column, 2 for the second column etc.) If so, this is a proprietary feature and is not recommended because of portability and (arguably) readability issues (But can admittedly be handy for a quick and dirty query).




回答3:


Tried kind a same query in MS SQL Server 2005

select distinct host from some_table group by 1,2,3

It error's out saying

Each GROUP BY expression must contain at least one column that is not an outer reference.

So this indicates that those 1,2,3 are nothing but column outer referrence



来源:https://stackoverflow.com/questions/6380002/what-do-comma-separated-integers-in-a-group-by-statement-accomplish

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!