小编典典

在SQL Server的同一列中串联一列

sql

嗨,我对串联一个列有疑问。我有两张桌子。

Table 1: Sales Order-> OrderID, ProductsOnHold (Should list product(s) on hold)
Table 2: Products-> ProductID, OnHold (boolean)
  • 一个销售订单可以有许多产品。
  • 产品可以具有保留,如果该订单具有该产品,则该销售订单将被保留。
  • 因此,可以保留一个或多个产品的销售订单。

如果订单被保留,我可以显示一种产品,但是如果有更多产品被保留,该怎么办-我又如何显示它们呢?这是我正在创建的视图。

到目前为止,这是我所做的:

(SELECT ProductName
 FROM Products with (NOLOCK)
 WHERE (OnHold = 1) AND (EXISTS   
    (SELECT CASE
               WHEN (COUNT(DISTINCT Product)> 1) THEN (Product + ', ' + Product)
               ELSE Product END AS ProductName
     FROM  SalesOrder WITH (NOLOCK) 
     GROUP BY OrderID ))) AS ProductsOnHold

所需的输出:

OrderID | ProductsOnHold
----------------------------------
    1   | P1, P2, P7                      
    2   |                
    3   | P1            
    4   | P1, P7, P8, P9, P15, P77

我的SQL查询中缺少任何内容吗?


阅读 157

收藏
2021-05-16

共1个答案

小编典典

假设您有2个表SalesOrder和Product的ProductID作为“关系”列,则可以联接这2个表,然后使用“ for xml”子句进行转置。

    select s1.OrderID,
stuff(
        (select ','+p.ProductName as [text()]
        from SalesOrder s
            join Product p on p.ProductID = s.ProductID and p.OnHold = true
        where s.OrderID = s1.OrderID
        group by p.ProductName 
        for xml path (''))
    ,1,1,'') as ProductsOnHold from SalesOrder s1 group by s1.OrderID

希望这可以帮助。

2021-05-16