How does GROUP BY work?
Suppose I have a table Tab1
with attributes - a1
, a2
, ... etc. None of the attributes are unique.
What will be the nature of the following query? Will it return a single row always?
SELECT a1, a2, sum(a3) FROM Tab1 GROUP BY a1, a2
Solution 1:
GROUP BY
returns a single row for each unique combination of the GROUP BY
fields. So in your example, every distinct combination of (a1, a2)
occurring in rows of Tab1
results in a row in the query representing the group of rows with the given combination of group by field values . Aggregate functions like SUM()
are computed over the members of each group.
Solution 2:
GROUP BY
returns one row for each unique combination of fields in the GROUP BY
clause. To ensure only one row, you would have to use an aggregate function - COUNT
, SUM
, MAX
- without a GROUP BY
clause.