TSQL使用CASE更新多个列,但取决于值

时间:2017-11-30 13:39:06

标签: sql-server tsql sql-update

这让我有点疯狂。我将解释我的问题的简化版本。我有两个表,源和目的地:

CREATE TABLE AMG_TDest(
ID INT,
Value1 INT,
Value2 INT,
Value3 INT,
Value4 INT)

CREATE TABLE AMG_TSource(
ID INT,
RowNumber INT,
Value INT)

INSERT INTO AMG_TDest VALUES (1, 0, 0, 0, 0), (2, 0, 0, 0, 0)

INSERT INTO AMG_TSource VALUES (1, 1, 1), (1, 2, 2), (1, 3, 3), (1, 4, 4), (2, 1, 10), (2, 2, 20), (2, 3, 30), (2, 4, 40)

我想根据TSource.RowNumber更新Destination表中的Value1,Value2,Value3和Value4。

最后我想得到的结果是目的地表:

ID V1   V2  V3  V4
1   1   2   3   4
2   10  20  30  40

我试过这个(有一些变化)

UPDATE AMG_TDest
SET
    Value1 = CASE WHEN  S.RowNumber = 1  THEN COALESCE(S.Value, 0) ELSE Value1 END,
    Value2 = CASE WHEN  S.RowNumber = 2 THEN COALESCE(S.Value, 0) ELSE Value2 END,
    Value3 = CASE WHEN  S.RowNumber = 3  THEN COALESCE(S.Value, 0) ELSE Value3 END,
    Value4 = CASE WHEN  S.RowNumber = 4  THEN COALESCE(S.Value, 0) ELSE Value4 END
FROM ( SELECT * FROM AMG_TSource ) AS S
INNER JOIN AMG_TDest D ON D.ID = S.ID

它只更新第一行的Value1和最后一行的Value4。我一直在和这个争斗几个小时,我无法让它发挥作用。如果有人有建议我真的很感激。

1 个答案:

答案 0 :(得分:0)

这是使用PIVOT

的方法
;WITH cteX
AS(
    SELECT PVT.ID
         , PVT.Value4
         , PVT.Value3
         , PVT.Value2
         , PVT.Value1 
    FROM 
    (
        SELECT S.ID
             , RN ='Value' + CAST(S.RowNumber AS varchar(10))
             , S.[Value]
        FROM dbo.AMG_TSource S
    ) X
    PIVOT
    (
        MAX(Value) FOR RN IN ([Value1],[Value2],[Value3],[Value4])
    ) PVT
)
UPDATE D
SET D.Value1 = X.Value1
    , D.Value2 = X.Value2
    , D.Value3 = X.Value3
    , D.Value4 = X.Value4
FROM 
    dbo.AMG_TDest   D
INNER JOIN
    cteX            X ON X.ID = D.ID

Pivot像这样对源数据集进行渐变

ID  Value4  Value3  Value2  Value1
1   4       3       2       1
2   40      30      20      10

然后,您需要加入ID列 用于更新目标表