在SQL中有条件地选择RowNum

时间:2016-08-11 05:11:45

标签: sql sql-server sql-server-2008 rownum

我写了一个查询,它返回了以下数据。

ID  EmpFirstName    EmpLastName RowNum
1     X                  Y        1
2     A                  B        1
3     A                  B        2

现在我想要RowNum为> 1的所有记录。例如,在这种情况下,我需要在输出中记录2和3。

如果我放条件RowNum >1那么我将只得到第三条记录,但我也想要2条。

3 个答案:

答案 0 :(得分:1)

假设您的查询是:

select ID, EmpFirstName, EmpLastName,
ROW_NUMBER() OVER (PARTITION BY EmpFirstName, EmpLastName ORDER BY ID) AS RowNum
FROM aTable

这是一个用于过滤掉任何重复值的经典查询。

为了有效地选择具有重复值的所有记录,我可以使用COUNT()窗口函数建议:

;with a as (
    select ID, EmpFirstName, EmpLastName,
    ROW_NUMBER() OVER (PARTITION BY EmpFirstName, EmpLastName ORDER BY ID) AS RowNum,
    COUNT(*) OVER (PARTITION BY EmpFirstName, EmpLastName) AS cnt
    FROM aTable
)
SELECT * FROM a where cnt > 1
ORDER BY EmpFirstName, EmpLastName

要测试它,请使用此查询:

drop table #tmp
CREATE table #tmp (ID int , EmpFirstName varchar(10) ,   EmpLastName varchar(10))
go
INSERT INTO #tmp VALUES 
    (1,'X','Y' )
    ,(2,'A','B')
    ,(3,'A','B')
    ,(4,'A','C')
    ,(5,'B','C')
    ,(6,'B','C')


;with a as (
    select ID, EmpFirstName, EmpLastName,
    ROW_NUMBER() OVER (PARTITION BY EmpFirstName, EmpLastName ORDER BY ID) AS RowNum,
    COUNT(id) OVER (PARTITION BY EmpFirstName, EmpLastName) AS cnt
    FROM #tmp
)
SELECT * FROM a where cnt > 1
ORDER BY EmpFirstName, EmpLastName

结果:

ID          EmpFirstName EmpLastName RowNum               cnt
----------- ------------ ----------- -------------------- -----------
2           A            B           1                    2
3           A            B           2                    2
5           B            C           1                    2
6           B            C           2                    2

答案 1 :(得分:0)

我制作样本数据并使用此查询

CREATE table #tmp (ID int , EmpFirstName varchar(10) ,   EmpLastName varchar(10) ,RowNum int)
INSERT INTO #tmp VALUES 
    (1,'X','Y',1)
    ,(2,'A','B',1)
    ,(3,'A','B',2)

SELECT ID,EmpFirstName,EmpLastName,RowNum
FROM (
    SELECT *
        ,ROW_NUMBER() OVER (ORDER BY ID) AS [NEWrownum]
    FROM #tmp
) q
WHERE q.NEWrownum > 1

答案 2 :(得分:0)

试试这个,

DECLARE @Result TABLE (ID INT, EmpFirstName VARCHAR(10), EmpLastName VARCHAR(10), RowNum INT)

INSERT INTO @Result
VALUES
     (1, 'X', 'Y', 1)
    ,(2, 'A', 'B', 1)
    ,(3, 'A', 'B', 2)

SELECT r1.*
FROM @Result r1
INNER JOIN (SELECT *        -- get duplicate records
            FROM @Result
            WHERE RowNum = 2                
            ) as r2 ON r1.EmpFirstName = r2.EmpFirstName
                    AND r1.EmpLastName = r2.EmpLastName