如何将行中的数据聚合成几个并执行其他SQL操作?

时间:2016-11-02 03:45:06

标签: sql sql-server r sqlcommand

我有一个表(从某些表中选择的结果,由Change列排序),如下所示:

ID      Change
1001    4
1002    4
1003    4
1004    3
1005    3
1006    2
...     ...

我想用以下数据更新另一个表格,如下所示:

update sometable set columnA=columnA + 4 where ID in (1001, 1002, 1003)
update sometable set columnA=columnA + 3 where ID in (1004, 1005)
update sometable set columnA=columnA + 2 where ID in (1006)
...

如何使用SQL命令执行此操作?

2 个答案:

答案 0 :(得分:0)

在测试样本数据

中尝试此操作
declare @t table(ID int,Change int)
insert into @t values (1001,4),(1002,4),(1003,4),(1004,3),(1005,3),(1006,2)

update s set s.columnA=s.columnA + t.change 
from sometable S
inner join @t t on s.id=t.id

答案 1 :(得分:0)

对于您的情况,以下是架构..

    CREATE TABLE #TAB(ID INT,      Change INT)
    INSERT INTO #TAB
    SELECT 1001 ,   4
    UNION ALL
    SELECT 1002,    4
    UNION ALL
    SELECT 1003  ,  4
    UNION ALL
    SELECT 1004,    3
    UNION ALL
    SELECT 1005 ,   3
    UNION ALL
    SELECT 1006,    2

现在我们可以使用For XML Path and Stuff和CTE来处理它,如下所示

    ;WITH CTE AS(
     SELECT DISTINCT CHANGE
    ,STUFF( (SELECT ', '+CAST(ID AS VARCHAR(100))  FROM #TAB T2 
     WHERE T2.Change= T.CHANGE  FOR XML PATH('')),1,1,'') ID_PK FROM #TAB T
    )
    SELECT 'UPDATE SOMETABLE SET COLUMN_A= COLUMN_A+ '+CAST(CHANGE AS VARCHAR(10))+' WHERE ID IN ('+ID_PK +') ;'  FROM  CTE