【问题标题】:Get the top ID in each group in SQL Server获取 SQL Server 中每个组中的顶部 ID
【发布时间】:2016-01-12 05:01:43
【问题描述】:

我想添加一列,其中包含每个组中的第一个。

示例:

Product       ID
Orange        1
Orange        2
Orange        3
Orange        4
Apple         5
Apple         6
Apple         7
Grapes        8
Grapes        9

期望的输出:

Product       ID
Orange        1
Orange        1
Orange        1
Orange        1
Apple         5
Apple         5
Apple         5
Grapes        8
Grapes        8

【问题讨论】:

  • 苹果:5、5、7? ,有点混乱。
  • MIN(ID) OVER(PARTITION BY Product) 可以解决问题。 SQL Fiddle

标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2008-r2


【解决方案1】:

你可以使用MIN(ID) OVER (PARTITION BY Product):

SELECT Product, 
       ID = MIN(ID) OVER (PARTITION BY Product)
FROM dbo.Products
ORDER BY ID

Demo

今日文章:Understanding the OVER clause

【讨论】:

  • 耶耶!谢谢!知道了! :)
【解决方案2】:

我认为蒂姆是正确的! 其他情况,您可以使用: SELECT P.Product FROM dbo.Products P CROSS APPLY (SELECT TOP 1 ID FROM dbo.Products WHERE Product = P.Product ORDER BY ID)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多