嗨,我对串联一个列有疑问。我有两张桌子。
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查询中缺少任何内容吗?
假设您有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
希望这可以帮助。