0
讓Multile行單列

我的問題:基於兩列

VALUES:  **TABLE A** 

ID  Number  Code 
ABC99  1   XYZ0 
ABC99  1   XyZ1 
ABC99  2   XZY2 
ABC99  3   XYZ1 
ABC99  3   XwZ4 
DEF88  5   QPR1 
DEF88  5   QPR2 
DEF88  6   QPS1 

期望輸出地說:ID應符合相應的數字和代碼級聯

輸出不同:

ID  Number  Code 
ABC99  1   XYZ0,XyZ1 
ABC99  2   XZY2 
ABC99  3   XYZ1,XwZ4 
DEF88  5   QPR1,QPR2 
DEF88  6   QPS1 

輸出:ID與一個唯一的編號匹配,並將多行(代碼)分隔成一行,並用逗號分隔(無論它們的數量多少)。

+0

重複的:http://stackoverflow.com/questions/31211506/how-stuff-and-for-xml-path-work-in-sql-server – McNets

回答

0
declare @t table (
    ID varchar(10), 
    Number int, 
    Code varchar(10) 
) 

insert into @t values 
('ABC99', 1, 'XYZ0'), 
('ABC99', 1, 'XyZ1'), 
('ABC99', 2, 'XZY2'), 
('ABC99', 3, 'XYZ1'), 
('ABC99', 3, 'XwZ4'), 
('DEF88', 5, 'QPR1'), 
('DEF88', 5, 'QPR2'), 
('DEF88', 6, 'QPS1'); 


select 
    ID, Number, 
    stuff((select ',' + Code from @t b 
      where a.ID = b.ID 
      and a.Number = b.Number 
      for XML PATH('') 
    ),1,1,'') Codes 
from @t a 
group by ID, Number; 
+0

它的工作原理。 謝謝你Gurv – Louis