首页 文章

使用聚合对分组数据进行SQL更新

提问于
浏览
1

我正在尝试更新表,首先按列1对数据进行分组,在我需要的每组数据中:按column2对数据进行排序,使用column3中的top值填充Column4(按column2排序)Columns1,3,4是varchar,第3列是int . 我尝试使用CTE和Top进行更新:

Update a
Set a.col4 = c.Best
From Table1 a,
(Select Top (1) Col3 as Best, Col1, Col2
From Table1
Group By Col1
Order By Col2 DESC) c
where a.Col1 = c.Col1

但它似乎是从表中选择最高值而不是从每个组中选择 . 有谁知道这里缺少什么或更简单的方法吗?
开始数据:
Col1 Col2 Col3 Col4
unit101 11 unit118 NULL
unit101 13 unit125 NULL
unit101 12 unit135 NULL
unit107 11 unit168 NULL
unit107 10 unit199 NULL

要求的结果:
Col1 Col2 Col3 Col4
unit101 11 unit118 unit125
unit101 13 unit125 unit125
unit101 12 unit135 unit125
unit107 11 unit168 unit168
unit107 10 unit199 unit168

第4列需要具有col3中的值,其中col 2处于数据中按col1分组的行的最大值 .

2 回答

  • 1

    使用'rank'确定'best'并将其添加到内连接中 . 下面是一个工作示例,并提供您要求的结果

    Update a
    Set a.col4 = c.Best
    From Table1 a
    inner join
    (
    Select 
        Col3 as Best,
        Col1,
        BestRank=RANK()over(partition by Col1 order by Col2 desc )
    From 
        Table1 b
    ) c on a.Col1 = c.Col1 and c.BestRank=1
    
  • 0

    你可以使用 CROSS APPLY

    Update a
    Set a.col4 = c.Best
    From Table1 a
     CROSS APPLY (Select Top (1) Col3 as Best, Col1, Col2
                  From Table1 t2
                  where a.Col1 = t2.Col1
                  Order By Col2 DESC) c
    

相关问题