获取第二个重复记录

时间:2015-02-13 04:50:17

标签: sql sql-server

我在加入::

之后得到了
CompanyID            EmpID                Emp_no      Location
-------------------- -------------------- -------------  -------------
1                    24                   100543         First.png
1                    24                   100543         Second.png

我想在select query中使用CASE WHEN选择第二个Record即Second.png。

2 个答案:

答案 0 :(得分:0)

检查一下。

declare @t table(CompanyID int, empid int, emp_no varchar(50), location varchar(100))    
insert into @t values (1,24,100543,'First.png'),(1,24,100543,'Second.png'),(1,25,100544,'Second.png'),(1,25,100544,'First.png')

select * from 
(
select 
    ROW_NUMBER() over(partition by companyid, empid order by companyid, empid ) rowno,  * 
from 
    @t
) a where rowno = 2 --and empid = 24  --here you can give empid to get particular employee detail

如果你想在单个选择语句中获得多个empid的第二个条目。

declare @t table(CompanyID int, empid int, emp_no varchar(50), location varchar(100))

insert into @t values (1,24,100543,'First.png'),(1,24,100543,'Second.png'),(1,25,100544,'Second.png'),(1,25,100544,'First.png')
,(1,26,100545,'First.png')

;with cte as
(
    select 
        *
    from 
    (
    select 
        ROW_NUMBER() over(partition by  empid order by empid ) rowno,  * 
    from 
        @t
    ) a 
),
cte1 as (
    select
            *,
            ROW_NUMBER() OVER(PARTITION BY empid ORDER BY rowno DESC) as RN
        from cte
)
select * from cte1 where rn = 1

答案 1 :(得分:0)

你可以写成:

;WITH CTE as
(
SELECT ROW_NUMBER() OVER ( PARTITION BY CompanyID,EmpID,Emp_no ORDER BY (SELECT 1))
       AS rownum,CompanyID,EmpID,Emp_no,Location
       FROM (SELECT * FROM @Test ) AS T
),CTE1 as
(
SELECT MAX(rownum) AS maxrownum, 
       CompanyID,
       EmpID,
       Emp_no      
FROM CTE
GROUP BY CompanyID,EmpID,Emp_no
)
SELECT T.CompanyID,T.EmpID,T.Emp_no,T.Location
FROM CTE T
JOIN CTE1 T1 ON T.CompanyID = T1.CompanyID
             AND T.EmpID = T1.EmpID
             AND T.Emp_no = T1.Emp_no
             AND T.rownum = T1.maxrownum

说明:

  1. 因为没有像我们可以识别的主键那样的列 首先是哪一行,你可以在分区窗口中写SELECT 1
  2. 一旦你获得了CompanyID,EmpID和Emp_no的每个组合的rownumber,你可以使用第二个CTE来获得每个组合的最大值 组合
  3. 只需使用maxrownumbers
  4. 从表中收集所有行的数据

    希望这会有所帮助:)