与此处的问题类似: http://forums.asp.net/t/1580379.aspx/1 我正在尝试将公共单元格合并到一个逗号分隔的单元格中,但是要跨内部连接。
我的SQL是:
SELECT DISTINCT tb_Order.OrderNumber, tb_Order.OrderId,
tb_Order.orderDate, tb_Order.OrderTotal,
tb_OrderStatus.OrderStatus, tb_Order.GroupOrderId,
tb_Venue.Title AS Venue
FROM tb_Order INNER JOIN tb_OrderItem ON tb_Order.OrderId = tb_OrderItem.OrderId
INNER JOIN tb_Show ON tb_OrderItem.ShowId = tb_Show.showId
INNER JOIN tb_OrderStatus ON tb_Order.OrderStatusId = tb_OrderStatus.OrderStatusID
INNER JOIN tb_Venue ON tb_Show.VenueId = tb_Venue.id
WHERE (tb_Order.OrderId = 705)
我需要[地点]以逗号分隔,如:
"Interactive Seating Chart Advanced, Interactive Seating Chart Mode Multi-Click"
答案 0 :(得分:0)
执行此操作的一种方法是使用行处理顺序的副作用来迭代填充变量,就像这样。这样做的缺点是它不能在简单的查询环境中工作,并且它不是最有效的解决方案。
DECLARE @venues varchar(max)
SET @venues = ''
SELECT @venues =
CASE WHEN @venues = '' THEN v.Title
ELSE @venues + ',' + v.Title END
FROM tb_Venue v
SELECT @venues
第二种方法是使用STUFF
和SQL Server XML扩展,如下所示:
SELECT DISTINCT v.Title,
(STUFF(
(SELECT ',' + v2.Title
FROM tb_Venue v2
-- uncomment this line if you are going
-- to aggregate only by something in the outer query
-- WHERE v2.GroupKey = v.GroupKey
ORDER BY v2.Title
FOR XML PATH(''), TYPE, ROOT
).value('root[1]','varchar(max)'),1,1,'')) as Aggregation
FROM tb_Venue v
基于CLR的解决方案通常是此用例中性能最高的解决方案,其中之一被描述为here以及其他一些不太理想的解决方案......
你的问题不是植根于设定逻辑的问题,所以没有一个干净的SQL解决方案......
答案 1 :(得分:0)
如果您具有SQL Server 2017(14.x)和更高版本,则可以使用STRING_AGG函数。
SELECT tb_Order.OrderNumber, tb_Order.OrderId,
tb_Order.orderDate, tb_Order.OrderTotal,
tb_OrderStatus.OrderStatus, tb_Order.GroupOrderId,
STRING_AGG(tb_Venue.Title, ',') AS Venue
FROM tb_Order INNER JOIN tb_OrderItem ON tb_Order.OrderId = tb_OrderItem.OrderId
INNER JOIN tb_Show ON tb_OrderItem.ShowId = tb_Show.showId
INNER JOIN tb_OrderStatus ON tb_Order.OrderStatusId = tb_OrderStatus.OrderStatusID
INNER JOIN tb_Venue ON tb_Show.VenueId = tb_Venue.id
WHERE (tb_Order.OrderId = 705)
GROUP BY tb_Order.OrderNumber, tb_Order.OrderId,
tb_Order.orderDate, tb_Order.OrderTotal,
tb_OrderStatus.OrderStatus, tb_Order.GroupOrderId