MySQL派生表中列值的总和

时间:2012-02-01 06:21:58

标签: mysql join sum case

这是我的疑问:

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)查询只返回1,但我知道情况并非如此。我试过在ans.authorID上添加一个组子句,但它没有效果。

如何获取tbl_solution_answers ans表中authorIDtbl_users.idAccepted的所有行的总和。

1 个答案:

答案 0 :(得分: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个为Accepted,则返回3 Accepted 1}}。