繁体   English   中英

MySQL派生表中列值的总和

[英]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表中获取所有行的总和,其中authorIDtbl_users.idauthorID ,而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行AnsweredAccepted则3行将作为Accepted返回。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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