如何在SQL查询中分隔所有以分号分隔的值

时间:2017-07-06 04:34:38

标签: sql-server

请按照附图所示的方式帮助您获取数据

突出显示的行实际上在“项目编号”字段

上分组

提前致谢

enter image description here

4 个答案:

答案 0 :(得分:1)

这是一种方式:

SELECT 
      it.[Item Number]
    , Values1 = STUFF(CAST((
        SELECT [text()] = ', ' +  CAST(it2.TotalItem AS varchar)    + ' x ' + it2.ItemName
        FROM dbo.Items it2
        WHERE it2.[Item Number] = it.[Item Number]
        FOR XML PATH(''), TYPE) AS VARCHAR(100)), 1, 2, '')

FROM ( 
    SELECT DISTINCT [Item Number]
    FROM dbo.Items
) it 

答案 1 :(得分:0)

以下应该工作:

SELECT distinct ItemNumber,SUBSTRING(
(SELECT ';' + TotalItem+' x '+ItemName
FROM YourTable
where ItemNumber=c.ItemNumber
ORDER BY ItemNumber
FOR XML PATH('')),2,200000 ) AS NewDescription from YourTable c
GO

答案 2 :(得分:0)

您可以使用 STRING_AGG

SELECT [Item Number],  STRING_AGG (CONCAT(TotalItem,'x',ItemName), ';') as tags 
FROM dbo.TableName
GROUP BY [Item Number];

答案 3 :(得分:0)

SELECT  t2.ItemNumber ,
        STUFF(( SELECT  ',' + CAST(TotalItem AS VARCHAR) + ' x ' + ItemName
                FROM    @MyTable t1
                WHERE   t1.ItemNumber = t2.ItemNumber
              FOR
                XML PATH('')
              ), 1, 1, '') AS NewDescription
FROM    @MyTable t2
GROUP BY t2.ItemNumber

DEMO