开发者

How can I combine two COUNT() statements into one and get the difference?

开发者 https://www.devze.com 2023-02-07 02:19 出处:网络
How can I combine the following two queries into one to get result as the difference of the two counts. Or where result is:

How can I combine the following two queries into one to get result as the difference of the two counts. Or where result is:

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


SELECT  SUM(votetypeid = @votetype1) - SUM(votetypeid = @votetype2)
FROM    votes
WHERE   userid = @userid
        AND votetypeid IN (@votetype1, @votetype2)


select sum(case when voteTypeId = @voteType1 then 1
                when voteTypeId = @voteType2 then -1
                else 0
           end) as result
    from votes
    where userId = @userId
0

精彩评论

暂无评论...
验证码 换一张
取 消