通过FOR XML PATH将主组连接到子组

时间:2015-04-23 16:36:15

标签: sql xml concat for-xml-path

我可以使用FOR XML PATH来连接多行以在一行中生成逗号分隔值,如下所示:

TMonth  Location    Degrees
Jan     Tokyo       7.0
Jan     New York    -0.2
Jan     Berlin      -0.9
Jan     London      3.9
Feb     Tokyo       6.9
Feb     New York    0.8
Feb     Berlin      0.6
Feb     London      4.2

SELECT t.Location, STUFF(
(SELECT ',' + convert(varchar(5), s.Degrees)
FROM MonthlyTemps s
WHERE s.Location = t.Location
--FOR XML PATH('')),1,1,'') AS CSV
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'') AS CSV
FROM MonthlyTemps AS t
GROUP BY t.Location

结果:

Location     CSV
Berlin     -0.9,0.6
London     3.9,4.2
New York   -0.2,0.8
Tokyo      7.0,6.9

现在,我确实需要结果(即“主要”组连接到“子组”的前面):

CSV
Berlin,-0.9,0.6
London,3.9,4.2
New York,-0.2,0.8
Tokyo,7.0,6.9

我尝试过几个不同的查询无济于事。我知道它就在那里盯着我,但我需要一双额外的眼睛来帮助我。任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:0)

使用字符串连接和子查询将两列与','连接起来。希望这项工作。

select Location + ',' + aa as 'CSV' from 
(
SELECT t.Location, STUFF(
(SELECT ',' + convert(varchar(5), s.Degrees) as aa
FROM MonthlyTemps s
WHERE s.Location = t.Location
--FOR XML PATH('')),1,1,'') AS CSV
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'),1,1,'') AS CSV
FROM MonthlyTemps AS t
GROUP BY t.Location
) as temp