【问题标题】:SQL: Compare entries in a single columnSQL:比较单列中的条目
【发布时间】:2013-07-19 15:19:12
【问题描述】:

我有一张桌子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 分组,然后按年份排序。我不知道如何比较候选人的条目。跟拥有有关系吗?我是查询数据库的新手。

【问题讨论】:

  • 写个程序怎么样。

标签: sql sql-server-2008


【解决方案1】:

试试这个

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

【讨论】:

    【解决方案2】:

    您可以使用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

    【讨论】:

    • 它也返回 p1。我猜它只检查去年。
    • (year &lt; c.year and DATEDIFF(year, [year], c.year) = 1?并且可能没有最后一个WHERE 子句?
    • 我认为你不能确定年份是连续的。否则会简单得多。
    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多