简体   繁体   中英

SQL sum aggregation not working as expected

I am trying to do feedback count and feedback responded. My query works fine but as soon as i try to aggregate it then it does not work as i expect it to.

SELECT 
feedback.client_id,
feedback.location_id,

@response:=(SELECT 
        event.created_date
    FROM
        event
    WHERE event.feedback_id = feedback.feedback_id) 'response',

CASE
    WHEN @response IS NOT NULL THEN 1
    ELSE 0
END 'responded'

FROM feedback

未汇总 This above works all fine. But now when i try to aggregate this table. Things dont work as i expect it to. I basically copy my sql and group by and add count function.

SELECT 
feedback.client_id,
feedback.location_id,

@response:=(SELECT 
        event.created_date
    FROM
        event
    WHERE event.feedback_id = feedback.feedback_id) 'response',

-- count feedback for each client+location
COUNT(*) 'count',

-- not working
SUM(CASE
    WHEN @response IS NOT NULL THEN 1
    ELSE 0
END) 'responded'

FROM
feedback

GROUP BY feedback.client_id , feedback.location_id;

聚合的

I should get 3 responded feedback for the first row and 19 for the second row but it shows 2 and 2.

You don't need to use a variable here, especially as it complicates the GROUP BY .
I suggest that it would be cleaner and more efficient to LEFT JOIN the table event. This would let you use the column from event elsewhere as needed.
I give you both options.

SELECT 
feedback.client_id,
feedback.location_id,
COUNT(*) 'count',
SUM(CASE
    WHEN (SELECT 
        event.created_date
    FROM
        event
    WHERE event.feedback_id = feedback.feedback_id) IS NOT NULL THEN 1
    ELSE 0
END) 'responded'
FROM
feedback
GROUP BY feedback.client_id , feedback.location_id;
SELECT 
f.client_id,
f.location_id,
COUNT(*) 'count',
SUM(CASE
    WHEN  e.created_date IS NOT NULL THEN 1
    ELSE 0
END) 'responded'
FROM
feedback f
LEFT JOIN event e
ON f.feedback_id = e.feedback_id
GROUP BY f.client_id , f.location_id;

db<>fiddle here

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