我很难让我的查询做我想做的事情......
如果我为一个UserId:2140173运行它似乎工作正常
Select UserId,
(Select Count(VoteTypeId) From SuggestedEditVotes where UserId = 2140173) as 'Total',
(Select Count(VoteTypeId) From SuggestedEditVotes where UserId = 2140173 and VoteTypeId = 2) As 'Accepted',
(Select Count(VoteTypeId) From SuggestedEditVotes where UserId = 2140173 and VoteTypeId = 3) As 'Rejected'
from SuggestedEditVotes
inner join Users on SuggestedEditVotes.UserId = Users.Id
where Users.Reputation > 2000 and UserId = 2140173
group by UserId
having Count(VoteTypeId) > 0
它返回
UserId Total Accepted Rejected
2140173 2230 1145 1085
但是当我尝试稍微修改它并为超过2000声望的所有用户运行它时,它并没有给我正确的结果:/
我坚持使用子Select语句,因为我不确定将什么放在他们的where
子句中。
这是我尝试的但它返回总数,我希望它是每个用户ID的计数
Select UserId,
(Select Count(VoteTypeId) From SuggestedEditVotes) as 'Total',
(Select Count(VoteTypeId) From SuggestedEditVotes where VoteTypeId = 2) As 'Accepted',
(Select Count(VoteTypeId) From SuggestedEditVotes where VoteTypeId = 3) As 'Rejected'
from SuggestedEditVotes
inner join Users on SuggestedEditVotes.UserId = Users.Id
where Users.Reputation > 2000
group by UserId
having Count(VoteTypeId) > 0
有人可以帮忙吗?
答案 0 :(得分:3)
试试这个:
SELECT UserId,
COUNT(VoteTypeId) AS 'Total',
COUNT(
CASE
WHEN VoteTypeId = 2
THEN VoteTypeId
ELSE NULL
END) AS 'Accepted',
COUNT(
CASE
WHEN VoteTypeId = 3
THEN VoteTypeId
ELSE NULL
END) AS 'Rejected'
FROM SuggestedEditVotes
INNER JOIN Users
ON SuggestedEditVotes.UserId = Users.Id
WHERE Users.Reputation > 2000
GROUP BY UserId
HAVING COUNT(VoteTypeId) > 0