如何连接sql中的所有行

时间:2017-12-21 13:48:53

标签: sql sql-server

我做了以下练习: 确定所有地址的平均距离,并在csv列表“CSV_Avg”中按地址连接平均距离,如表Address _Distances中所示。

这是表格的样子

enter image description here

这是查询应该做的事情

enter image description here

到目前为止我已经完成了这个但是我找不到如何连接单个列中所有行的方法

这是我的查询的样子

SELECT DISTINCT 

      [id_address]    
      ,sum([distance])/count([distance]) as "AVGDistance"
      ,CONCAT([id_address],'=',[distance]) as "CSV_AVG"
  FROM [Test].[dbo].[View_2]
  WHERE [id_address] IS NOT NULL

  Group by [id_address],[distance]

1 个答案:

答案 0 :(得分:0)

你可以这样做:

WITH CTE
AS
(
  SELECT 
      [id_address]    
      ,sum([distance])/count([distance]) as "AVGDistance"
  FROM view_2
  WHERE [id_address] IS NOT NULL
  Group by [id_address]
)
SELECT *, (SELECT  STUFF((SELECT ',' + CONCAT([id_address],'=',AVGDistance) 
                         FROM CTE
                        FOR XML PATH(''), TYPE
                       ).value('.', 'NVARCHAR(MAX)') 
                          , 1, 1, '')) AS CSV_AVG
FROM CTE;

这将为您提供与您正在寻找的完全相同的结果:

| id_address | AVGDistance |                               CSV_AVG |
|------------|-------------|---------------------------------------|
|         21 |       72.84 | 21=72.840000,35=49.195000,95=1.690000 |
|         35 |      49.195 | 21=72.840000,35=49.195000,95=1.690000 |
|         95 |        1.69 | 21=72.840000,35=49.195000,95=1.690000 |