查询以将多行合并为单行

时间:2019-07-10 05:59:35

标签: sql-server tsql string-aggregation

我有一张桌子,上面有以下信息:

ITEM  WH  BATCH  DOC NO
CLD1  FN   B1      3
CLD1  FN   B1      3
CLD1  FN   B2      3
CLD1  FN   B2      3
CLD1  FN   B3      3
CLD1  FN   B4      3

这是我用来带来上述值的代码:

select T0.item,t0.wh,t0.batchnum from oibt t0 where t0.DOCNO = '3' and t0.Wh = 'FN'

我需要这样的输出:

ITEM  WH  BATCH
CLD1  FN   B1,B2,B3,B4

我也使用了STUFF和For XML编码,但是没有得到想要的输出。

3 个答案:

答案 0 :(得分:4)

SELECT ITEM, 
       WH, 
       BATCH = STUFF((SELECT ',' + BATCH
                      FROM oibt
                      WHERE [DOC NO] = '3'
                      GROUP BY BATCH
                      FOR XML PATH ('')), 1, 1, '') 
FROM oibt
GROUP BY ITEM, WH

答案 1 :(得分:2)

如果您使用的是SQL Server 2016或更高版本,则可以使用内置的STRING_AGG函数,而不必执行XML FOR和STUFF的繁琐的传统组合:

SELECT  ITEM
        ,WH
        ,BATCH = STRING_AGG(BATCH,',')
FROM
(
    SELECT  DISTINCT 
            ITEM, WH, BATCH
    FROM    OIBT O
    WHERE   DOCNO = '3' 
    AND     Wh = 'FN'
) IQ
GROUP   BY ITEM, WH

答案 2 :(得分:1)

以下查询应执行您想要的操作:

SELECT ITEM
    ,WH
    ,BATCH = STUFF( (SELECT DISTINCT ', ' + BATCH FROM table1 t WHERE t.ITEM = ITEM FOR XML PATH ('')),1,1,'')
FROM table1
GROUP BY ITEM, WH

根据您的代码示例进行了更新,

SELECT T0.Item
    ,T0.Wh
    ,[BATCH REF NO]  = STUFF((SELECT DISTINCT '; ' + US.Batch FROM OIBT US WHERE US.DOCNO = '3' AND US.Wh = Wh AND US.ITEM = ITEM FOR XML PATH('')), 1, 1, '')
FROM OIBT T0 
WHERE T0.DOCNO = '3' AND T0.WH = 'FN' 
GROUP BY T0.ITEM,T0.WH ORDER BY T0.Item