SQL:比较单个列中的条目

时间:2013-07-19 06:23:47

标签: sql sql-server-2008

我有一个表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进行分组,然后按年份排序。我无法弄清楚如何比较候选人的条目。这有什么关系吗?我是新来的查询数据库。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 Fiddle