使用SQL Server获得最高计数

时间:2014-02-11 02:09:49

标签: sql-server

我目前正在开发投票系统。我写了一个查询来获得所有投票,但它只显示所有投票获得者,而不是最高投票。我应该在查询中添加什么来执行我需要的内容。这是代码。

SELECT DISTINCT 
   b.idnumber, b.candidate_name, semester,  
   (SELECT COUNT(rslt_ccandidateid) FROM rslt_mstr 
    WHERE rslt_ccandidateid = idnumber) AS 'numberOfVotes', 
   b.position, b.program, b.position_categ, b.party_name, 
   b.school, b.yearLevel, a.hierarchy           
FROM
   cddt_mstr b 
INNER JOIN 
   Position_mstr  a ON a.scposition_name = b.position 
WHERE 
   b.POSITION_CATEG = 'SUPREME COUNCIL CANDIDATES'  
   AND semester = '2ND SEMESTER A.Y. 2012-2013'  
ORDER BY 
   a.hierarchy, 'numberOfVotes' DESC

1 个答案:

答案 0 :(得分:0)

下面的内容可能有用。我假设rslt_ccandidateid不是投票值有一些其他列,我调用[vote_column_name],其中包含投票值。我也假设投票值是一个整数列。最后,我假设你不希望所有选票的总和只是所有选票中的最高票。

SELECT DISTINCT b.idnumber, b.candidate_name, semester, (
        SELECT MAX([vote_column_name])
        FROM rslt_mstr
        WHERE rslt_ccandidateid = idnumber
        GROUP BY rslt_ccandidateid
        ) AS 'numberOfVotes', b.position, b.program, b.position_categ, b.party_name, b.school, b.yearLevel, a.hierarchy
FROM cddt_mstr b
INNER JOIN Position_mstr a ON a.scposition_name = b.position
WHERE b.POSITION_CATEG = 'SUPREME COUNCIL CANDIDATES'
    AND semester = '2ND SEMESTER A.Y. 2012-2013'
ORDER BY a.hierarchy, 'numberOfVotes' DESC