Skip to content
Advertisement

Query Totaling Multiple columns and grouping by another

I am trying to get some totals of multiple records based on Location – but get totals for multiple columns to present back – basically there are various locations and each location has different species and totals at that location.

Without doing something really ugly – I have no idea of the best approach – any suggestions?

I have a table
Record
RecordID, Location, Species1, Species2, Species3


1, Loc1, 3, NULL,1
2, Loc2, NULL, 12, NULL
3, Loc2, 2, 2, 2
4, Loc1, 1, 2, 3
5, Loc4, 3, NULL, NULL

I need to get the following data like this:

Location | Species1 | Species2 | Species3
Loc1 | 4 | 2 | 4
Loc2 | 2 | 14 | 2
Loc4 | 3 | NULL | NULL

Advertisement

Answer

SELECT Location,
       SUM(ISNULL(Species1, 0)) AS Species1,
       SUM(ISNULL(Species2, 0)) AS Species2,
       SUM(ISNULL(Species3, 0)) AS Species3
FROM Record
GROUP BY Location
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement