SQL某些行的总和

时间:2015-12-09 03:39:18

标签: sql-server

我是SQL的新手。我正在为选举创建一个数据库,我有2个表,Party表和Candidate表。

我创建一个查询,返回候选人的ridingName,partyName,firstName,lastName,投票数,以及每次投票数最多的候选人投票的总票数#骑术。但是,我在返回每次骑行投票总票数的部分遇到了麻烦。

Party = {partyName, partyWebsite}
Candidate = {partyName, ridingName, firstName, lastName, votes} 
(votes here being the number of votes cast for that particular candidate)

这是我到目前为止所拥有的......

SELECT C.ridingName, P.partyName, C.FirstName, C.LastName, C.votes, sum(C.votes) AS totalVotes --I tried to use sum to find total votes, but didn't quite work...
FROM Candidate C, Party P
WHERE C.votes = --this is to find the top candidate per riding
    (SELECT MAX(C1.votes)
    FROM Candidate C1
    WHERE C.ridingName = C1.ridingName) AND
    P.partyName = C.partyName   
GROUP BY C.ridingName, C.FirstName, C.LastName,P.partyName, C.votes
ORDER BY C.ridingName

示例输入+输出:

enter image description here

2 个答案:

答案 0 :(得分:0)

就像Tim提到的那样,添加样本输入和输出数据可能会有很大帮助。根据我的理解,你想要一个像这样的查询:

with test as (
  select partyname, ridingname, firstname, lastname, 
         sum(votes) as totalvotes
  from candidate
  group by partyname, ridingname, firstname, lastname
)
select * from test
inner join (
  select ridingname, max(totalvotes) as maxvotes
  from test
  group by ridingname
) a on test.ridingname = a.ridingname and test.totalvotes = a.maxvotes

示例如下:http://sqlfiddle.com/#!3/e95f3/6http://sqlfiddle.com/#!3/077bd/1

编辑:

啊,只是有点不同:http://sqlfiddle.com/#!3/a102d/8

with test as (
  select partyname, ridingname, firstname, lastname, 
         sum(votes) as totalvotes
  from candidate
  group by partyname, ridingname, firstname, lastname
)
select partyname, test.ridingname, firstname, lastname,
       totalvotes, allvotes 
from test
inner join (
  select ridingname, max(totalvotes) as maxvotes, sum(totalvotes) as allvotes
  from test
  group by ridingname
) a on test.ridingname = a.ridingname and test.totalvotes = a.maxvotes

答案 1 :(得分:0)

尝试此查询,尝试根据Candidate表中的示例输入生成所需的输出。

SELECT t1.ridingName, t1.partyName, t1.firstName, t1.lastName, t2.votes, t2.totalVotes
FROM Candidate t1
INNER JOIN
(
    SELECT c.ridingName, MAX(votes) AS votes, SUM(votes) AS totalVotes
    FROM Candidate c
    GROUP BY c.ridingName
) t2
ON t1.ridingName = t2.ridingName AND t1.votes = t2.votes