3

我有一张桌子Candidates,与CandidateNameIDYearOfElectionVotes于当年收到。我想让所有投票数逐年增加的候选人。

样本条目:

CandidateId  year                    votes
------------ ----------------------- ----------
p1           2008-01-01 00:00:00     120       
p2           2008-01-01 00:00:00     15        
p3           2008-01-01 00:00:00     18        
p1           2009-01-01 00:00:00     115       
p2           2009-01-01 00:00:00     20        
p3           2009-01-01 00:00:00     20        
p1           2010-01-01 00:00:00     125       
p2           2010-01-01 00:00:00     19        
p3           2010-01-01 00:00:00     21   

样本输出:

CandidateID
--------------
p3

我已经尝试过的:

我尝试分组candidateID,然后按年份排序。我不知道如何比较候选人的条目。跟拥有有关系吗?我是查询数据库的新手。

4

2 回答 2

2

尝试这个

CREATE TABLE #Candidates
    ([CandidateId] varchar(12), [year] DATETIME, [votes] INT)
;

INSERT INTO #Candidates
    ([CandidateId], [year], [votes])
VALUES
    ('p1', '2008-01-01 00:00:00', '120'),
    ('p2', '2008-01-01 00:00:00', '15'),
    ('p3', '2008-01-01 00:00:00', '18'),
    ('p1', '2009-01-01 00:00:00', '115'),
    ('p2', '2009-01-01 00:00:00', '20'),
    ('p3', '2009-01-01 00:00:00', '20'),
    ('p1', '2010-01-01 00:00:00', '125'),
    ('p2', '2010-01-01 00:00:00', '19'),
    ('p3', '2010-01-01 00:00:00', '21')
;

SELECT [CandidateId] FROM #Candidates
WHERE [CandidateId] NOT IN 
(
    SELECT T1.[CandidateId] FROM #Candidates T1
    INNER JOIN #Candidates T2 ON T2.[CandidateId] = T1.[CandidateId] 
    AND T1.[YEAR] > T2.[YEAR] AND T1.votes < T2.votes
)
GROUP BY [CandidateId]

DROP TABLE #Candidates
于 2013-07-19T07:17:34.060 回答
1

你可以通过使用来做到这一点not exists

   select candidateId from candidates c
   where not exists 
   (
    select 1 
    from candidates 
    where candidateId = c.candidateId and year < c.year and votes > c.votes
   ) 
   group by candidateId 
   having count(*) = 
   (select count(*) from candidates where candidateId = c.candidateId)

SQL小提琴

于 2013-07-19T06:31:10.223 回答