如何将以下两个查询合并为一个以获得result
作为两个计数的差异。或结果如下:
result = vote1 - vote2
SELECT COUNT(id) AS vote1 FROM votes WHERE votes.voteTypeId = @voteType1 AND votes.userId = @userId
SELECT COUNT(id) AS vote2 FROM votes WHERE votes.voteTypeId = @voteType2 AND votes.userId = @userId
答案 0 :(得分:3)
SELECT SUM(votetypeid = @votetype1) - SUM(votetypeid = @votetype2)
FROM votes
WHERE userid = @userid
AND votetypeid IN (@votetype1, @votetype2)
答案 1 :(得分:1)
select sum(case when voteTypeId = @voteType1 then 1
when voteTypeId = @voteType2 then -1
else 0
end) as result
from votes
where userId = @userId