你可以做使用UVPIVOT相同
測試數據
declare @exmp_test table(id int, v1 int,v2 int,v3 int,v4 int)
insert into @exmp_test
select 1, 2 , 4 , 6, 7 union all
select 1 , 4 , 77 , 3 , 8 union all
select 2 , 4 , 16 , 1 , 8
查詢
;with cte as(select row_number() over(order by id) as rn,t.v1 + t.v2 + t.v3 + t.v4 as sumallversions,t.* from @exmp_test t)
,unpvtcte as(select rn,id as versions,vals from (select rn,[v1],[v2],[v3],[v4] from cte)t
unpivot (vals for id in([v1],[v2],[v3],[v4]))as unpvt)
update @exmp_test
set id = y.sumall
from @exmp_test e
join (
select c.id,c.id + x.minvals as sumall,c.sumallversions, x.minvals from cte c
join(select rn,MIN(vals) minvals from unpvtcte group by rn)x on x.rn = c.rn) y
on y.id = e.id
and y.sumallversions = e.v1 + e.v2 + e.v3 + e.v4
輸出:
id v1 v2 v3 v4
3 2 4 6 7
4 4 77 3 8
3 4 16 1 8
如果連續兩列具有相同的價值,這就是最低值應發生什麼情況? – CMG 2009-12-23 13:31:05
然後,我們應該去最左邊一欄。即如果v2和v4具有相同的值並且它是最小值,那麼我們將選擇v2列以添加[id]值。 – Paresh 2009-12-23 13:33:24
查看http://www.sqlusa.com/bestpractices/minimum/。 **(0.5 *((@ColumnA + @ColumnB) - abs(@ColumnA - @ColumnB)))** – 2009-12-23 13:50:42