如何将多行中的一列连接起来,然后将该值插入另一行的单列中?

时间:2018-07-27 19:09:23

标签: sql-server tsql

因此,我们有这张桌子:

    CAR_PARTS
    ID   CAR_ID  PART_NAME       
    1    11      Steering Wheel  
    2    22      Steering Wheel 
    3    22      Headlights      

我们还有此表:

    CARS
    ID   CAR_MODEL        PART_NAME_LIST
    11   Mustang          
    22   Camaro           
    33   F-150            

如何像这样将数据添加到PART_NAME_LIST列:

    CARS
    ID   CAR_MODEL        PART_NAME_LIST
    11   Mustang          Steering Wheel
    22   Camaro           Steering Wheel, Headlights
    33   F-150            (No parts were found)

1 个答案:

答案 0 :(得分:2)

好的。对于SQL Server 2017之前的SQL Server版本,请尝试以下操作:

declare @CAR_PARTS table(ID int, CAR_ID int, PART_NAME nvarchar(128));
insert @CAR_PARTS values
  (1, 11, 'Steering Wheel'),  
  (2, 22, 'Steering Wheel'), 
  (3, 22, 'Headlights');

declare @CARS table(
  ID int,
  CAR_MODEL nvarchar(30),
  PART_NAME_LIST nvarchar(max) null);

insert @CARS(ID, CAR_MODEL) values
  (11, 'Mustang'),
  (22, 'Camaro'),
  (33, 'F-150');

select
  c.ID,
  c.CAR_MODEL,
  stuff(cast((
    select
      ',' + cp.PART_NAME [text()]
    from @CAR_PARTS cp
    where cp.CAR_ID = c.ID
    for xml path('')
  )as nvarchar(max)), 1, 1, '') PART_NAME_LIST
from @CARS c;

在SQL Server 2017中,可以使用string_agg函数:

select
  c.ID,
  c.CAR_MODEL,
  string_agg(cp.PART_NAME,',') PART_NAME_LIST
from @CARS c left join @CAR_PARTS cp
  on c.ID = cp.CAR_ID
group by c.ID, c.CAR_MODEL;

对此在线here进行检查。

UPD :可能的UPDATE语句已添加到演示中。