表格结构:
Solution_Votes :
解决方案:
代码:
SELECT
*,
(SELECT SUM(CASE WHEN voteUp = 1 THEN 1 ELSE 0 END)
FROM Solutions_Votes) AS VoteCountUp,
(SELECT SUM(CASE WHEN voteDown = 0 THEN 1 ELSE 0 END)
FROM Solutions_Votes) AS VoteCountDown
FROM
Solution
当我运行此查询时,它会为voteUpCount
和voteDownCount
的每一行提供计数。我需要基于解决方案ID的计数,以便每个解决方案都有其投票和减少投票的计数。如果有人可以提供帮助,将不胜感激。提前谢谢!
答案 0 :(得分:0)
只需使用条件聚合。在你的情况下,这很简单:
solutions
如果某些解决方案没有投票并且您想要包含它们,则只需要solutions
表。
编辑:
您将以各种方式包含select s.*, ss.VoteCountUp, ss.VoteCountDown
from solutions s left join
(select sv.solutionid,
sum(case when sv.voteUp = 1 then 1 else 0 end) as VoteCountUp,
sum(case when sv.voteDown = 0 then 1 else 0 end) as VoteCountDown
from solutions_votes sv
group by sv.solutionid
) ss
on s.solutionid = ss.solutionid;
。这是一个:
0xffffffffffffff8c