4

类似于这里的问题: 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)

在此处输入图像描述

我需要 [venue] 以逗号分隔,例如:

"Interactive Seating Chart Advanced, Interactive Seating Chart Mode Multi-Click"
4

2 回答 2

1

如果您有 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
于 2020-10-22T15:10:28.317 回答
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

第二种方法是使用STUFFSQL 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 的解决方案通常是此用例中性能最高的解决方案,此处描述了其中一个解决方案以及大量其他不太理想的解决方案......

您的问题不是根源于集合逻辑,因此没有干净的 SQL 解决方案......

于 2012-04-27T01:36:26.937 回答