我正在尝试构建一个查看具有三列的表的视图;建筑,车道,很多。我需要能够动态循环遍历表格,以便在一行中显示Building,Lane和Lot。
样品:
>Building Lane Lot
> 1 1001 56789
> 1 1002 12489
> 1 1002 37159
> 1 1002 71648
> 3 3001 27489
> 3 3001 67154
> 3 3002 47135
> 3 3003 84271
> 3 3003 96472
> 3 3003 94276
结果
> Building Lane Lots
> 1 1001 56789
> 1 1002 12489, 37159, 71648
> 3 3001 27489, 67154
> 3 3002 47135
> 3 3003 84271, 96472, 94276
我尝试了一个递归联盟,但收到一条消息,说我已超出最大数量100。 我也尝试了一个循环,但它只是继续前进,并没有按照我的希望进行连接。 到目前为止,表格中有一个建筑物在一条车道上有超过300个批次编号,而且可能会有更多的人。
答案 0 :(得分:1)
看起来您正在寻找类似于以下脚本(see this SQL Fiddle example)的内容:
DECLARE @row TABLE (
A VARCHAR(1),
AA VARCHAR(1),
B VARCHAR(4)
)
INSERT INTO @row VALUES(1,1,1001)
INSERT INTO @row VALUES(1,1,1002)
INSERT INTO @row VALUES(1,1,1003)
INSERT INTO @row VALUES(1,2,1001)
INSERT INTO @row VALUES(2,1,1001)
INSERT INTO @row VALUES(2,1,1002)
INSERT INTO @row VALUES(2,1,1003)
INSERT INTO @row VALUES(2,1,1004)
INSERT INTO @row VALUES(2,1,1005)
INSERT INTO @row VALUES(2,2,1001)
INSERT INTO @row VALUES(2,2,1002)
INSERT INTO @row VALUES(3,1,1001)
SELECT *
FROM @row
SELECT r1.A
, r1.AA
, STUFF((SELECT ', ' + r2.B AS [text()]
FROM @row r2
WHERE r1.A = r2.A AND r1.AA = r2.AA
ORDER BY r2.B
FOR XML PATH('')),1,1,'') AS "Row"
FROM @row r1
GROUP BY A, AA
因此,对于您的查询,它看起来像这样:
SELECT r1.Building
, r1.Lane
, STUFF((SELECT ', ' + r2.Lot AS [text()]
FROM YourTable r2
WHERE r1.Building = r2.Building AND r1.Lane = r2.Lane
ORDER BY r2.Lot
FOR XML PATH('')),1,1,'') AS "Row"
FROM YourTable r1
GROUP BY Building, Lane