我有一个包含3列,id,name和vote的表。他们有很多寄存器。我需要以最佳的选票余额归还寄存器。投票类型为“是”和“否”。
是 - >加1 不 - >减1
此列投票是一个字符串列。我正在使用SQL SERVER。
示例:
必须为我返回 Ann
答案 0 :(得分:3)
使用条件聚合来计算卡南在答案中建议的投票数
如果你真的只想要1条记录,那么就可以这样做:
SELECT TOP 1
name
,SUM(CASE WHEN vote = 'yes' THEN 1 ELSE -1 END) AS VoteTotal
FROM
@Table
GROUP BY
name
ORDER BY
VoteTotal DESC
这不允许绑定,但你可以使用这种方法对响应进行排名并给你结果使用RowNum只获得1个结果或RankNum来获得关系。
;WITH cteVoteTotals AS (
SELECT
name
,SUM(CASE WHEN vote = 'yes' THEN 1 ELSE -1 END) AS VoteTotal
,ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY SUM(CASE WHEN vote = 'yes' THEN 1 ELSE -1 END) DESC) as RowNum
,DENSE_RANK() OVER (PARTITION BY 1 ORDER BY SUM(CASE WHEN vote = 'yes' THEN 1 ELSE -1 END) DESC) as RankNum
FROM
@Table
GROUP BY
name
)
SELECT name, VoteTotal
FROM
cteVoteTotals
WHERE
RowNum = 1
--RankNum = 1 --if you want with ties use this line instead
以下是使用的测试数据,并且将来不要只是将测试数据的图像花费2分钟来制作临时表或表变量,以便您要求帮助的人不必! / p>
DECLARE @Table AS TABLE (id INT, name VARCHAR(25), vote VARCHAR(4))
INSERT INTO @Table (id, name, vote)
VALUES (1, 'John','no'),(2, 'John','no'),(3, 'John','yes')
,(4, 'Ann','no'),(5, 'Ann','yes'),(6, 'Ann','yes')
,(9, 'Marie','no'),(8, 'Marie','no'),(7, 'Marie','yes')
,(10, 'Matt','no'),(11, 'Matt','yes'),(12, 'Matt','yes')
答案 1 :(得分:0)
使用此代码,
;with cte as (
select id, name, case when vote = 'yes' then 1 else -1 end as votenum from register
) select name, sum(votenum) from cte group by name
您可以根据此获得最大或最小..
答案 2 :(得分:0)
这个给出了每个人的“是”费率:
SELECT Name, SUM(CASE WHEN Vote = 'Yes' THEN 1 ELSE 0 END)/COUNT(*) AS Rate
FROM My_Table
GROUP BY Name