SQL Server:按字符串连接分组

3
我有一个问题。我知道这个问题之前已经被问过了。我查看了相关的问题,但是我无法让我的 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的解决方案。
谢谢!

建议:将您的模式发布在http://sqlfiddle.com/上,以便我们更轻松地进行操作。*编辑-这可能与您的问题有关:http://stackoverflow.com/questions/10405362/concatenate-multiple-rows-from-multiple-tables/10405475 - YS.
你不是加入了错误的字段吗?ID 看起来和 part_ID 是一样的。 - xQbert
编号Id是车辆ID。PartID是零件的ID。PartID在CARS和CAR_PARTS表中都很常见。描述从CAR_PARTS表中获取并连接以查找汽车所拥有的零件(描述)。 - EngelbertCoder
2个回答

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接