我在加入::
之后得到了CompanyID EmpID Emp_no Location
-------------------- -------------------- ------------- -------------
1 24 100543 First.png
1 24 100543 Second.png
我想在select query中使用CASE WHEN
选择第二个Record即Second.png。
答案 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
说明:
SELECT 1
。希望这会有所帮助:)