查询将多行变成单行

Query to get multiple row into single row

我有一个 table,其中有以下信息:

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 编码,但我没有得到想要的输出。

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

以下查询应该可以满足您的要求:

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 

如果您使用的是 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