从组中选择具有特定值的行?

时间:2013-04-28 16:31:35

标签: tsql

从下表中,如果Project.Date组有一个失败和成功,我想保留失败行,但如果是单行(如其余的那样),那么无论状态如何,都要保留该行。例如,我想保留第一行,丢弃第二行,并将其余部分保留在下面的表格中。

╔═════════╦══════════╦═════════╗
║ PROJECT ║   DATE   ║ STATUS  ║
╠═════════╬══════════╬═════════╣
║ HLM     ║ 20130422 ║ Fail    ║
║ HLM     ║ 20130422 ║ Success ║
║ HLM     ║ 20130423 ║ Fail    ║
║ HLM     ║ 20130424 ║ Success ║
║ HLM     ║ 20130425 ║ Fail    ║
║ HLM     ║ 20130426 ║ Success ║
╚═════════╩══════════╩═════════╝

1 个答案:

答案 0 :(得分:2)

WITH records
AS
(
    SELECT  [Project], [Date], [Status],
            ROW_NUMBER() OVER (PARTITION BY [Project], [Date]
                                ORDER BY [Status]) rn
    FROM    TableName
)
SELECT  [Project], [Date], [Status]
FROM    records
WHERE   rn = 1

输出

╔═════════╦══════════╦═════════╗
║ PROJECT ║   DATE   ║ STATUS  ║
╠═════════╬══════════╬═════════╣
║ HLM     ║ 20130422 ║ Fail    ║
║ HLM     ║ 20130423 ║ Fail    ║
║ HLM     ║ 20130424 ║ Success ║
║ HLM     ║ 20130425 ║ Fail    ║
║ HLM     ║ 20130426 ║ Success ║
╚═════════╩══════════╩═════════╝