大家好,我有一个关于连接专栏的问题。我有两张桌子。
Table 1: Sales Order-> OrderID, ProductsOnHold (Should list product(s) on hold)
Table 2: Products-> ProductID, OnHold (boolean)
因此暂停销售订单可暂停1个或多个产品。
如果订单处于暂停状态,我可以显示一个产品, 但如果有更多的产品被搁置怎么办 - 我怎么能显示它们? 这是我正在创建的视图。
这是我到目前为止所做的:
(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查询中缺少什么?
答案 0 :(得分:0)
我的解决方案[我不确定我是否理解你的问题]
用户功能
create function inonerow (@orderid int)
returns nvarchar(max)
begin
declare @data nvarchar(max)
SELECT @data =coalesce(@data + ',','')+ CONVERT(varchar,prodid) from SalesOrder
inner join product on product.prodid = salesorder.prodid where orderid=@orderid and product.oshold = 1
return @data
end
select distinct orderid, dbo.inonerow(orderid) from salesorder
inner join product on product.prodid = salesorder.prodid
where product.onhold = 1
希望这有效:)
答案 1 :(得分:0)
假设您有2个表SalesOrder和Product with ProductID作为“关系”列,您可以加入这两个表,然后使用“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
希望这有帮助。