如果列值与先前行不同,请选择行

时间:2013-03-04 04:54:11

标签: sql sql-server tsql sql-server-2005

我有一张如下表格

No. FName Age  Tag
1    abc   22    c
2    xyz   60    c
3    pqr   62    i
4    abc   22    i
5    abc   32    i

我希望将结果作为

返回
No. FName Age  Tag
1    abc   22    c
2    xyz   60    c
3    pqr   62    i
5    abc   32    i

要求是,如果Name行的列Age AND tag=c and tag=i值相同,则tag=i行应< strong>不被选中。

行号1和行号。 4具有相同的值(Name,age)=(abc,22)但行4具有tag = i。因此,必须省略(abc,22,i)之上的第4行。我怎么能这样做?

2 个答案:

答案 0 :(得分:6)

WITH records
AS
(
    SELECT  No, FName, Age, Tag,
            ROW_NUMBER() OVER (PARTITION BY FName, Age
                                ORDER BY Tag ASC) rn
    FROM    tableName
    WHERE   TAG IN ('c','i')
)
SELECT  No, FName, Age, Tag
FROM    records
WHERE   rn = 1

如果您在TAG上有其他特殊值,

WITH records
AS
(
    SELECT  No, FName, Age, Tag,
            ROW_NUMBER() OVER (PARTITION BY FName, Age
                                ORDER BY CASE WHEN TAG = 'c' THEN 0 ELSE 1 END ASC) rn
    FROM    tableName
    WHERE   TAG IN ('c','i')
)
SELECT  No, FName, Age, Tag
FROM    records
WHERE   rn = 1
ORDER   BY No

更新1

SELECT Fname, Age, MIN(tag) Tag
FROM   TableName
WHERE  TAG IN ('c','i')
GROUP  BY Fname, Age

答案 1 :(得分:4)

我认为如果已经存在具有相同tagagename ='c'的行,则可以忽略tag ='i'的所有行:

select * from TableName t1
where not exists 
          (select 1 
           from TableName 
           where FNAme = t1.FNAme and Age = t1.Age and t1.Tag = 'i' and tag = 'c')