I’m pretty new to SQL and am trying to figure out if there’s a way to aggregate the date into new column. For instance, below is a sample set of date. I want to take all the type ‘2’ and create new columns
Mem Balance Type New 1 2500 2 0 2 722 66 1 3 9422 1 0 4 122 2 1 5 788 66 1
So instead of having it like above, it would be like
Mem Type2Balance Type66Balance Type2New Type66New 1 2622 0 1 0 2 0 1510 0 2
Is there a way to do this in SQL? I thought maybe using IF statements within a case statement? I’m not asking for it to be done for me, more of looking for specifics that I can read about to make this happen. Thank you!
Advertisement
Answer
It seems like you want:
select case when type = 2 then sum(balance) else 0 end type2balance, case when type = 66 then sum(balance) else 0 end type66balance, case when type = 2 then sum(new) else 0 end type2new, case when type = 66 then sum(new) else 0 end type66new from mytable where type in (2, 66) group by type
I am not sure what logic you want for column Mem
in the resulset. It that’s just a row number, then:
select row_number() over(order by type) mem, case when type = 2 then sum(balance) else 0 end type2balance, case when type = 66 then sum(balance) else 0 end type66balance, case when type = 2 then sum(new) else 0 end type2new, case when type = 66 then sum(new) else 0 end type66new from mytable where type in (2, 66) group by type
We could put the conditional expression on type
inside the aggregate function, but it does not really make sense since you are grouping by type
already. In that case, that would be:
select row_number() over(order by type) mem, sum(case when type = 2 then balance else 0 end) type2balance, sum(case when type = 66 then balance else 0 end) type66balance, sum(case when type = 2 then new else 0 end) type2new, sum(case when type = 66 then new else 0 end) type66new from mytable where type in (2, 66) group by type