MySQL 派生表中列值的总和

标签 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.id >已接受为 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'似乎有效。现在如果 authorIDtbl_solution_answers有 8 行,它们都将返回为 Answered如果说其中 3 个是 Accepted那么 3 返回为 Accepted .

关于MySQL 派生表中列值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9091696/

相关文章:

mysql - 带有 bindParam() 的 PDO 返回语法错误

MySQL从两个表中删除多列

java - 输出正在打印两种情况[java]

ruby-on-rails - rails | PG::分组错误

mysql - 无法使连接正常工作

javascript - 逗号分隔字符串的总和

c++ - 对如何在 c++ 中编写 for 循环(包括 for all 加法)感到困惑

mysql - 在不影响当前记录值的情况下向现有列添加自动增量

sql - 在此 SQL 语句中使用 SELECT 无效

mysql - 如何在mysql中实现地理空间引用系统