【问题标题】:MySQL sum of column value from derived tableMySQL派生表中列值的总和
【发布时间】:2012-02-01 06:21:57
【问题描述】:

这是我的查询:

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。

【问题讨论】:

    标签: mysql join sum case


    【解决方案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' 似乎有效。现在,如果 tbl_solution_answers 中的 authorID 有 8 行,它们都将作为 Answered 返回,如果其中 3 个是 Accepted,则 3 作为 Accepted 返回。

    【讨论】:

      猜你喜欢
      • 2013-03-20
      • 2016-11-05
      • 2020-07-03
      • 2021-06-06
      • 1970-01-01
      • 2017-09-09
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多