2017-05-31 20 views
1

我試圖通過首先按列1, 對數據進行分組來更新表,我需要: 按列2對數據進行排序 使用頂部填充Column4列3的值(按列2排序) 列1,3,4是varchar,列3是int。 我試圖用一個CTE的更新和Top爲:使用聚合的分組數據的SQL更新

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 unit11 unit125
unit101 13 unit125 uni T125
unit101 12 unit135 unit125
unit107 11 unit168 unit168
unit107 10 unit199 unit168

柱4只需要具有從COL3的值,其中第2欄第是在數據的行的最大值由COL1作爲分組。

+0

喲可以提供[MCVE]的結果(http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an- MCVE換什麼,似乎對我將要-A-極簡單的SQL查詢)?如果我們可以看到輸入/輸出的樣本,回答這樣的問題更容易。 –

回答

1

使用「排名」來確定「最好的」,並補充說,自己內心的加入。下面是一個工作exampole,並提供您要求

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

完美地工作,謝謝! – user8091579

+0

很酷的模式@ user1529235,現在我很好奇我想比較它與CROSS APPLY – hardkoded

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 
+0

當我運行這個時,我得到一個錯誤:Table1.Col3在選擇列表中無效,因爲它不包含在聚合函數或group by子句中。 – user8091579

+0

我修復了問題@ user8091579,但要知道您選擇的解決方案比此更快。 – hardkoded

+0

這很好,謝謝。 – user8091579