选择具有最高ID和指定列值的行

时间:2013-04-26 14:39:58

标签: sql sql-server

我的SQL查询有问题。我有下表:

╔════╦═══════════════╦═════════════╦══════════╗
║ ID ║     NAME      ║    CITY     ║ PCNUMBER ║
╠════╬═══════════════╬═════════════╬══════════╣
║  1 ║ John Doe      ║ New York    ║       42 ║
║  2 ║ John Doe      ║ New York    ║       42 ║
║  3 ║ John Doe      ║ New York    ║       42 ║
║  4 ║ John Doe      ║ Los Angeles ║       42 ║
║  5 ║ Ellen Ripley  ║ Nostromo    ║     2092 ║
║  6 ║ James T. Kirk ║ Riverside   ║     2233 ║
║  7 ║ Henry Jones   ║ Chicago     ║     1899 ║
╚════╩═══════════════╩═════════════╩══════════╝

现在我想获得具有指定PCNUMBER(可以超过1)的行,但它只能为每个唯一的PCNUMBER返回1个结果

所以让我们假设我想要PCNUMBER 42和2092的数据。结果将是:

╔════╦══════════════╦═════════════╦══════════╗
║ ID ║     NAME     ║    CITY     ║ PCNUMBER ║
╠════╬══════════════╬═════════════╬══════════╣
║  4 ║ John Doe     ║ Los Angeles ║       42 ║
║  5 ║ Ellen Ripley ║ Nostromo    ║     2092 ║
╚════╩══════════════╩═════════════╩══════════╝

我尝试了很多东西,但我似乎无法产生这个:(希望你们能帮助我。

如果有人已经有类似的问题,我很抱歉,但我找不到一个。

2 个答案:

答案 0 :(得分:2)

SQL Server支持Common Table ExpressionWindowing Functions

WITH records
AS
(
    SELECT  ID, Name, City, PCNUMBER,
            ROW_NUMBER() OVER(PARTITION BY PCNUMBER ORDER BY ID DESC) rn
    FROM    TableName
)
SELECT  ID, Name, City, PCNUMBER
FROM    records
WHERE   rn = 1 AND
        PCNUMBER IN (42, 2092)

输出

╔════╦══════════════╦═════════════╦══════════╗
║ ID ║     NAME     ║    CITY     ║ PCNUMBER ║
╠════╬══════════════╬═════════════╬══════════╣
║  4 ║ John Doe     ║ Los Angeles ║       42 ║
║  5 ║ Ellen Ripley ║ Nostromo    ║     2092 ║
╚════╩══════════════╩═════════════╩══════════╝

答案 1 :(得分:1)

单向;

select T.* from T
    inner join (
        select 
            max(id) id
        from T
        where PCNUMBER in (42, 2092)
        group by PCNUMBER
    ) mx on mx.id = T.id