is GROUP BY used only with aggregate functions ?
Can anyone give an example where it is used not in conjunction with aggregate functions.
is GROUP BY used only with aggregate functions ? Can anyone give an example
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
SELECT with GROUP BY can be used as an alternative to SELECT DISTINCT. Pranay Rana’s example is essentially equivalent to
If you want an example where the preference of GROUP BY over DISTINCT is justified, here’s one. Say, you want to return items that only occur once in a table:
As you can see, the query only returns a non-aggregated column.
It still uses an aggregate function, though, even if not in the SELECT clause. There may be situations where you must prefer GROUP BY to DISTINCT while not needing to use aggregate functions at all, but I’ll have to be platform specific at this point.
In particular, if you are using SQL Server, you will find a difference between the results of the following two statements:
#1:
#2:
(If you aren’t, you can still see the results for yourself using Stack Exchange Data Explorer.)
Both statements are meant to return distinct items ranked. However, only the first statement (with GROUP BY) returns the results as expected, while the latter (with DISTINCT) returns all items.
Obviously, ranking functions in SQL Server are evaluated after GROUP BY, but before DISTINCTThe reason is, the SELECT clause in SQL Server is evaluated after GROUP BY, but before DISTINCT, which makes you prefer GROUP BY over DISTINCT in this case. (Thanks @ypercube for nudging me in the right direction.)