当前位置: 代码迷 >> Sql Server >> update多个字段到一个字段应该怎么写
  详细解决方案

update多个字段到一个字段应该怎么写

热度:47   发布时间:2016-04-24 10:05:10.0
update多个字段到一个字段应该如何写
比如说表1
ID     S1    S2    S3
1        1        1       1
2         1        2       3
3         3         3        3
表2
ID   S1   S5   S6
1     1               x
2      3              x
把表1中S1一样的S2数据写入S5中

表中S5原来都是空的,想要得到如下效果
ID   S1   S5   S6
1     1      1,2    x
2      3         3     x

用Update应该怎么写,有点纠结,谢谢!
------解决方案--------------------

create table 表1
(ID int,S1 int,S2 int,S3 int)

insert into 表1
 select 1,1,1,1 union all
 select 2,1,2,3 union all
 select 3,3,3,3

create table 表2
(ID int,S1 int,S5 varchar(30),S6 varchar(10))

insert into 表2
 select 1,1,'','x' union all
 select 2,3,'','x'


-- 更新
update c
 set c.S5=isnull(d.s5,'')
 from 表2 c
 left join
 (select a.S1,
         stuff((select ','+rtrim(b.S2)
                from 表1 b
                where b.S1=a.S1
                for xml path('')),1,1,'') 's5'
  from 表1 a
  group by a.S1) d on c.S1=d.S1


-- 结果
select * from 表2

/*
ID          S1          S5                             S6
----------- ----------- ------------------------------ ----------
1           1           1,2                            x
2           3           3                              x

(2 行受影响)
*/
  相关解决方案