Skip to content
Advertisement

SQL GROUP BY IN CASE STATEMENT

i have one table

enter image description here

i would like to classify the apple as below

enter image description here

i try to add code as below, but its not like what I expected

SELECT apple_id, sum(apple_wgt)
,case when apple_colour != 'no colour' then sum(apple_wgt) as 'apple_wgt_no_colour'
,case when apple_colour = 'no colour' then sum(apple_wgt) as 'apple_wgt_colour'
from apples
group by apple_id, apple_wgt

I try this code also, but got error

SELECT apple_id, sum(apple_wgt)
,case when apple_colour != 'no colour' then sum(apple_wgt) end as 'apple_wgt_no_colour'
,case when apple_colour = 'no colour' then sum(apple_wgt) end as 'apple_wgt_colour'
from apples
group by apple_id, 
case when apple_colour != 'no colour' then sum(apple_wgt) end,
case when apple_colour = 'no colour' then sum(apple_wgt) end

Advertisement

Answer

You want conditional aggregation here, which involves summing over the CASE expression:

SELECT
    apple_id,
    SUM(apple_wgt) AS apple_wgt,
    SUM(CASE WHEN apple_colour != 'no colour'
             THEN apple_wgt ELSE 0 END) AS apple_wgt_no_colour
FROM yourTable
GROUP BY
    apple_id;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement