SOQL GROUP BY
SOQL does support grouping by multiple fields. The grouping order is from left to right.
Example! Find the count of clinics in various states and cities.
This query will return a table of this type:
Using Aliases in GROUP BY
In SQL, we can alias any column being fetched from the database table, but in SOQL, this is not allowed.
However, we can still alias fields fetched when the SOQL query contains a group by clause.
Note that alias notation does not use
as like SQL does.
It is also important to note, that even if you don’t specify an alias, all aggregated fields automatically get an implied alias in the form
expr(n) where n starts from 0, and from left to right.
For Instance, Query:
Count(Id) automatically becomes
Then to access these fields, you have to use their respective aliases in Apex.