如何在mssql中对此结果集进行concat分组

时间:2016-10-28 12:13:59

标签: sql sql-server group-concat

如何修改和应用以下结果的连接

这是第一张表:

DECLARE @item_tbl TABLE ( ItemId INT,Title NVARCHAR(20))
INSERT INTO @item_tbl VALUES (1,'Title 1'),(2,'Title 2')
,(3,'Title 3'),(4,'Title 4'),(5,'Title 5')

这是第二张表:

DECLARE @item_ref TABLE (ReferenceId INT, FromItemId INT,
ToItemId INT) 
INSERT INTO @item_ref VALUES(1,1,2),(2,1,3),(3,4,5),(4,5,1)

表1和表1之间存在一些相互关系。表2

SELECT AA.Title, ISNULL(BB.Hasreferenceto,'') Hasreferenceto,
ISNULL(CC.Isreferencedfrom,'') Isreferencedfrom FROM  
@item_tbl AA LEFT JOIN ( SELECT A.FromItemId, B.Title Hasreferenceto
FROM @item_ref A LEFT JOIN @item_tbl B  ON A.ToItemId =B.ItemId
 ) BB ON AA.ItemId = BB.FromItemId
LEFT JOIN ( SELECT C.ToItemId, D.Title Isreferencedfrom 
FROM @item_ref C LEFT JOIN @item_tbl D ON C.FromItemId = D.ItemId
) CC ON AA.ItemId = CC.ToItemId

这给了我:

+---------+------------------+--------------------+
| Title   | Hasreferenceto   | Isreferencedfrom   |
+---------+------------------+--------------------+
| Title 1 | Title 2          | Title 5            |
+---------+------------------+--------------------+
| Title 1 | Title 3          | Title 5            |
+---------+------------------+--------------------+
| Title 2 |                  | Title 1            |
+---------+------------------+--------------------+
| Title 3 |                  | Title 1            |
+---------+------------------+--------------------+
| Title 4 | Title 5          |                    |
+---------+------------------+--------------------+
| Title 5 | Title 1          | Title 4            |
+---------+------------------+--------------------+

我想要的是:

+---------+------------------+--------------------+
| Title   | Hasreferenceto   | Isreferencedfrom   |
+---------+------------------+--------------------+
| Title 1 | Title 2, Title 3 | Title 5            |
+---------+------------------+--------------------+
| Title 2 |                  | Title 1            |
+---------+------------------+--------------------+
| Title 3 |                  | Title 1            |
+---------+------------------+--------------------+
| Title 4 | Title 5          |                    |
+---------+------------------+--------------------+
| Title 5 | Title 1          | Title 4            |
+---------+------------------+--------------------+

有人可以帮忙吗?

0 个答案:

没有答案