SQL Server:按字符串连接分组

时间:2012-10-21 12:40:47

标签: sql-server group-by concatenation for-xml-path

我有一个问题。我知道之前有人问过。我查看了相关的问题但是我无法使用我的SQL脚本。

这是我的问题:

SELECT T1.PART_ID, T2.ID, T2.DESCRIPTION
FROM #TEMP T1 
INNER JOIN #TEMP2 T2 ON T1.PART_ID = T2.PART_ID
ORDER BY T2.ID

表:

PART_ID |  ID        |    DESCRIPTION
----------------------------------
10002   |  1182505   |   Tagfahrlichtschaltung
80029   | 1182505    |   Bluetooth
20004   | 1212866    |    Kindersitzbefestigung
10045   |  1212866   |    Lederlenkradrriegelung
11908   |  1257946   |    Airbag
22346   | 1257946    |    Automatic

我希望得到如下结果:

ID       | LISTOFPARTS
-----------------------------
1182505  |  "10002 : Tagfahrlichtschaltung ; 80029 : Bluetooth  "
1212866  |  "20004 : Kindersitzbefestigung ; 10045 : Lederlenkradrriegelung"
1257946  |  "11908 : AIRBAG ; 22346 : AUTOMATIC"

我想它必须是XML PATH的东西,但我无法让它工作。 任何人都可以重写查询,以便它返回按字符串分组和连接的结果吗?

有或没有XML PATH的解决方案将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

这将有效 -

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