Waller
Waller

Reputation: 1873

Greatest-n per group MSSQL

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.

Upvotes: 0

Views: 713

Answers (3)

Vicky_Burnwal
Vicky_Burnwal

Reputation: 981

;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 

Upvotes: 1

Waller
Waller

Reputation: 1873

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 

Upvotes: 0

Kannan Kandasamy
Kannan Kandasamy

Reputation: 13959

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

Upvotes: 0

Related Questions