每组 Greatest-n MSSQL
Greatest-n per group MSSQL
我正在使用 SQL-server 2008
我的 table 看起来是这样的:
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
我试图只获得 max_period 最大的名字,由 Employee_ID
输出如下所示:
max_period Employee ID Preferred Name
2016-10-19 00:00:00.000 16317 James Hello
谁能帮我解决这个问题?这看起来很简单,但让我很头疼。
你可以尝试使用 row_number() over()
;with cte as (
select *, RowN = row_number() over (order by max_Period desc) from YourTable
) select * from cte where RowN = 1
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
;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
你也可以用 GROUP BY 来完成
select MAX(max_period), EmployeeID , PreferredName FROM Table1 GROUP BY EmployeeID , PreferredName
我正在使用 SQL-server 2008
我的 table 看起来是这样的:
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
我试图只获得 max_period 最大的名字,由 Employee_ID
输出如下所示:
max_period Employee ID Preferred Name
2016-10-19 00:00:00.000 16317 James Hello
谁能帮我解决这个问题?这看起来很简单,但让我很头疼。
你可以尝试使用 row_number() over()
;with cte as (
select *, RowN = row_number() over (order by max_Period desc) from YourTable
) select * from cte where RowN = 1
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
;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
你也可以用 GROUP BY 来完成
select MAX(max_period), EmployeeID , PreferredName FROM Table1 GROUP BY EmployeeID , PreferredName