从多行到单值的多个Id值

时间:2015-10-23 13:00:52

标签: sql sql-server

我的表格看起来像下面的

ID     LINE_NUMBER  CODE          DATA
39311   1           AXFP-20090    A
39311   2           AXFP-20227    B
39311   3           AXFP-20067    B
39311   4           AXFP-20337    B
39311   5           AXFP-20081    B
39311   6           AXFP-20048    B
39311   7           AXFP-20025    B
39311   8           AXFP-22371    B
39311   9           AXFP-20176    B
39311   10          AXFP-20278    B
39311   11          AXFP-21838    B
39311   14          AXFP-92035    C
41681   1           AXFP-99999    A
41681   2           AXFP-58229    A
41681   3           AXFP-51166    A
41681   5           AXFP-21848    C
41681   6           AXFP-58191    C
41681   7           AXFP-61481    C
41681   8           AXFP-21757    A
41681   9           AXFP-32704    C
41681   10          AXFP-60037    B
41681   11          AXFP-21849    B
41681   12          AXFP-34021    C
41681   13          AXFP-34072    C

我需要将每个id的数据合并为一行。以下列格式保存行号,代码和数据

enter image description here

任何人都有任何想法我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

select  ID     ,
Data=Stuff((SELECT ' ' + CAST(LINE_NUMBER  as VARCHAR(255)) + ')' + CODE  +  ' ' + DATA  FROM t t1 WHERE t1.ID =t.ID        
 FOR XML PATH (''))
             , 1, 1, '' )
from t
GROUP BY ID   

FIDDLE