【问题标题】:Greatest-n per group MSSQL每组最大 n 个 MSSQL
【发布时间】:2017-03-02 12:01:06
【问题描述】:

我使用的是 SQL-server 2008

我的桌子是这样的:

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

我试图仅通过 Employee_ID 获取 max_period 最大的名称

输出如下所示:

max_period  Employee ID Preferred Name
2016-10-19 00:00:00.000 16317   James Hello

有人可以帮我解决这个问题吗?这似乎很容易,但首先让我很头疼。

【问题讨论】:

  • 在派生表/CTE 中使用RANKROW_NUMBER() OVER (PARTITION BY Employee_ID ORDER BY max_period DESC) as r,然后过滤WHERE r = 1

标签: sql sql-server sql-server-2008 greatest-n-per-group


【解决方案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 

【讨论】:

    【解决方案2】:

    你可以尝试使用 row_number() over()

    ;with cte as (
      select *, RowN = row_number() over (order by max_Period desc) from YourTable
     ) select * from cte where RowN = 1
    

    【讨论】:

      【解决方案3】:
      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 
      

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 1970-01-01
        • 2013-08-23
        • 2023-04-08
        • 2013-04-16
        • 2022-08-20
        • 2022-01-06
        • 2013-05-27
        • 2015-07-31
        相关资源
        最近更新 更多