Someone sent me a SQL query where the
GROUP BY
clause consisted of the statement: GROUP BY 1
.
This must be a typo right? No column is given the alias 1. What could this mean?
Am I right to assume that this must be a typo?
Answers
It means to group by the first column regardless of what it's called. You can do the same
with
ORDER BY
.
In addition to grouping by the field name, you may also group by ordinal, or position the
field is.
This is generally unadvised if you're grouping on something specific, since the table/view
structure may change; additionally, it is more difficult to read (credit: Yuck). However if you
are returning a unique set of something, then it is okay.
It will group by the column position you put after the group by clause.
for example if you run '
SELECT SALESMAN_NAME, SUM(SALES) FROM SALES GROUP BY 1
'
it will group by
SALESMAN_NAME
.
One risk on doing that is if you run '
Select *
' and for some reason you recreate the table
with columns on a different order, it will give you a different result than you would expect.
0 comments:
Post a Comment