简体   繁体   中英

SQL GROUP BY IN CASE STATEMENT

i have one table

在此处输入图片说明

i would like to classify the apple as below

在此处输入图片说明

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

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;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM