[英]MySQL sum of column value from derived table
这是我的查询:
SELECT usr.id,
count(DISTINCT sol.id) as 'Asked',
count(DISTINCT ans.id) as 'Answered',
sum(DISTINCT CASE ans.accepted WHEN 1 THEN 1 ELSE 0 end) as 'Accepted'
FROM tbl_users usr
LEFT JOIN tbl_solutions sol on sol.authorID = usr.id
LEFT JOIN tbl_solution_answers ans on ans.authorID = usr.id
group by usr.id, sol.authorID
我上面的sum(DISTINCT CASE ans.accepted WHEN 1 THEN 1 ELSE 0 end)
查询sum(DISTINCT CASE ans.accepted WHEN 1 THEN 1 ELSE 0 end)
只返回1,尽管我知道不是这样。 我尝试在ans.authorID
上添加一个group子句,但是它没有任何效果。
如何从tbl_solution_answers ans
表中获取所有行的总和,其中authorID
为tbl_users.id
的authorID
,而Accepted
为1。
SELECT usr.id,
count(DISTINCT sol.id) as 'Asked',
count(DISTINCT ans.id) as 'Answered',
count(DISTINCT case ans.accepted when 1 then ans.id end) as 'Accepted'
FROM tbl_users usr
LEFT JOIN tbl_solutions sol on sol.authorID = usr.id
LEFT JOIN tbl_solution_answers ans on ans.authorID = usr.id
group by usr.id, sol.authorID, ans.authorID
经过如此多的排列count(DISTINCT case ans.accepted when 1 then ans.id end) as 'Accepted'
似乎有效。 现在,如果authorID
中的tbl_solution_answers
有8行,它们将全部作为Answered
返回,并且如果说其中3行Answered
被Accepted
则3行将作为Accepted
返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.