[英]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.我基本上是复制我的 sql 和 group by 并添加计数功能。
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.我应该得到第一行的 3 个响应反馈和第二行的 19 个响应反馈,但它显示 2 和 2。
You don't need to use a variable here, especially as it complicates the GROUP BY .您不需要在这里使用变量,特别是因为它使GROUP BY复杂化。
I suggest that it would be cleaner and more efficient to LEFT JOIN the table event.我建议LEFT JOIN表事件会更干净,更有效。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.