我如何计算并从表中获得最高结果?

时间:2018-01-25 22:28:57

标签: sql sql-server tsql

我的表是:

id | candidate | position      | partylist
---+-----------+---------------|----------
1  | Bryan     | President     | LEAP
2  | Miko      | Vice President| SHARE
5  | Nico      | Vice President| LEAP
3  | Miko      | Vice President| SHARE
4  | Bryan     | President     | LEAP
6  | Miko      | Vice President| SHARE
7  | Bryan     | President     | LEAP
7  | Joe       | President     | SHARE

我需要计算投票数并从每个职位获得最高结果,结果将是:

candidate | position       | partylist | votes
----------+----------------+-----------+------
Bryan     | President      | LEAP      | 3
Miko      | Vice President | SHARE     | 3

我只试过这个:

SELECT candidate
    , partylist
    , COUNT(*) AS votes
FROM tblvotes
WHERE position = 'President'
GROUP BY candidate
    , partylist
ORDER BY votes DESC

我不知道如何得到我想要的结果。

1 个答案:

答案 0 :(得分:1)

如果您手动查看每个位置

select top 1 * from
(
    SELECT candidate, partylist, COUNT(*) AS Votes
    FROM tblvotes
    WHERE position = 'President'
    GROUP BY candidate, partylist
) res
order by Votes desc

如果您希望以最高票数显示整个结果,请尝试以下

;with mycte as 
(SELECT candidate, partylist, position, COUNT(*) AS Votes
FROM tblvotes
GROUP BY candidate, partylist , position
),
myRanking as 
(
select 
rank() over (partition by position order by votes desc) pos
,candidate, partylist, position, votes
from myCte
)
select * from myRanking where pos = 1