I have the following table test
id Actual Budget CA RUB_ID
-------------------------------------------
1 20 30 201 902
1 2 330 202 902
1 220 130 207 90
1 21 30 20 12
How can get the following result
Actual Budget CA
20 130 12
I need to do sum Actual if RUB_ID =902 , sum Budget if RUB_ID =90 ,sum CA if RUB_ID =12
select
id,
case
when RUB_ID = 902 then sum(Actual) AS Actual
else case
when RUB_ID = 90
then sum(Budget) as Budget
else case
when RUB_ID = 12 then sum(CA) as CA
FROM
TEST
group by
id
The query does not return what I am looking for , how can I modify it ?
Put your case statements inside the sum functions
select
sum(case when RUB_ID = 902 then Actual else 0 end) Actual,
sum(case when RUB_ID = 90 then Budget else 0 end) Budget,
sum(case when RUB_ID = 12 then CA else 0 end) CA
from test where RUB_ID IN (902,90,12)
if you want these results by id
select
id,
sum(case when RUB_ID = 902 then Actual else 0 end) Actual,
sum(case when RUB_ID = 90 then Budget else 0 end) Budget,
sum(case when RUB_ID = 12 then CA else 0 end) CA
from test where RUB_ID IN (902,90,12)
group by id
Something like this:
SELECT
id
, SUM(CASE RUB_ID WHEN 902 THEN Actual ELSE 0 END) as Actual
, SUM(CASE RUB_ID WHEN 90 THEN Budget ELSE 0 END) as Budget
, SUM(CASE RUB_ID WHEN 12 THEN CA ELSE 0 END) as CA
FROM TEST
GROUP BY id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.