2

我有一个 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 ║
╚════╩══════════════╩═════════════╩══════════╝

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

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

4

2 回答 2

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 ║
╚════╩══════════════╩═════════════╩══════════╝
于 2013-04-26T14:41:30.977 回答
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
于 2013-04-26T14:46:01.007 回答