Reputation: 21
I want to sum value in the same column but depending on certain creteria in different columns i.e.
value column1 column2 column3
11 a x m
45 b y n
50 b z p
12 c x p
So e.g. I want the total sum for 'Value' when column1 = b & column2 = z & column n
I used the following syntax:
sum(case when column1 = b & column2 = z & column n then value end) total
which worked but I am dealing with lot of columns, so is there an easier way to do this. I was thinking loops, but can't make sense of loops in SQL.
Upvotes: 2
Views: 59
Reputation: 14173
SELECT SUM(value) FROM table GROUP BY col1, col2, col3
and if needed for a specific set you can use
SELECT SUM(value) FROM table GROUP BY col1, col2, col3 HAVING col1='a' AND col2='n' AND col3='c'
Upvotes: 1