SQL Server : Group by string concatenation

独自空忆成欢 提交于 2019-12-01 00:53:00

This will work -

DECLARE @TABLE TABLE (PART_ID INT,ID INT, DESCRIPTION VARCHAR(100))

INSERT INTO @TABLE 
VALUES
(10002   ,1182505   ,   'Tagfahrlichtschaltung')
,(80029   , 1182505    ,   'Bluetooth')
,(20004   , 1212866    ,    'Kindersitzbefestigung')
,(10045   ,  1212866   ,    'Lederlenkradrriegelung')
,(11908   ,  1257946   ,    'Airbag')
,(22346   , 1257946    ,    'Automatic')

;WITH SUBQUERY
AS
(
    SELECT ID,(CAST(PART_ID AS VARCHAR(12)) + ' : ' + DESCRIPTION) 'CONCATED'
    FROM @TABLE 
)

SELECT ID, LEFT(pre_trimmed.CONCATED , LEN(pre_trimmed.CONCATED )-1) AS LISTOFPARTS
FROM SUBQUERY AS extern
CROSS APPLY
(
    SELECT CONCATED + ','
    FROM SUBQUERY AS intern
    WHERE extern.ID = intern.ID
    FOR XML PATH('')
) pre_trimmed (CONCATED)
GROUP BY ID, pre_trimmed.CONCATED

http://sqlfiddle.com/#!3/d41d8/5441

create table #Temp (PART_ID bigint, ID bigint, DESCRIPTION nvarchar(max))

insert into #Temp
select 10002, 1182505, 'Tagfahrlichtschaltung' union all
select 80029, 1182505, 'Bluetooth' union all
select 20004, 1212866, 'Kindersitzbefestigung' union all
select 10045, 1212866, 'Lederlenkradrriegelung' union all
select 11908, 1257946, 'Airbag' union all
select 22346, 1257946, 'Automatic'

select 
    T1.ID,
    stuff(
        (
            select ' ; ' + cast(T2.PART_ID as nvarchar(max)) + ' : ' + T2.DESCRIPTION
            from #TEmp as T2
            where T2.ID = T1.ID 
            for xml path(''), type
        ).value('data(.)', 'nvarchar(max)')
    , 1, 3, '') as LISTOFPARTS
from #TEMP as T1 
group by T1.ID
order by T1.ID
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!