I am using SQL-server 2008
My table looks like so:
max_period Employee ID Preferred Name
2016-10-19 00:00:00.000 16317 James Hello
2015-10-31 00:00:00.000 16317 Jimmy Hello
I am trying to only get the name with the greatest max_period, by Employee_ID
output would look like this:
max_period Employee ID Preferred Name
2016-10-19 00:00:00.000 16317 James Hello
Can someone help me solve this? It seems easy and first but is causing me a real headache.
答案 0 :(得分:0)
you can try using row_number() over()
;with cte as (
select *, RowN = row_number() over (order by max_Period desc) from YourTable
) select * from cte where RowN = 1
答案 1 :(得分:0)
SELECT *
FROM (SELECT max(period) as max_period, [Employee ID], [Preferred Name],
ROW_NUMBER() OVER (PARTITION BY [Employee ID] ORDER BY period DESC) rank
FROM STG.tbl_HR_BI_feed
where [Employee ID] = '16317'
group by [Employee ID], [Preferred Name], period) a
WHERE a.rank = 1
答案 2 :(得分:0)
;with cte
AS
(
select max_period ,EmployeeID , PreferredName, ROW_NUMBER() OVER (PARTITION BY Employee_ID ORDER BY max_period DESC) as RN From Table1
)
SELECT * from cte WHERE RN = 1
You can do it with GROUP BY as well
select MAX(max_period), EmployeeID , PreferredName FROM Table1 GROUP BY EmployeeID , PreferredName