我有以下表格
产品 - 存储为productid ProductRelation - 存储链接的产品ID
DECLARE @Product table(ProductID int)
DECLARE @ProductRelation TABLE (FirstProductID int,SecondProductID int)
INSERT INTO @Product
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL
SELECT 9
UNION ALL
SELECT 10
--SELECT * FROM @Product
INSERT INTO @ProductRelation
SELECT 1,2
UNION ALL
SELECT 3,5
UNION ALL
SELECT 2,6
UNION ALL
SELECT 1,4
UNION ALL
SELECT 1,4
--SELECT * FROM @ProductRelation
SELECT ProductID,'Not Linked' AS 'Relation' FROM @Product
UNION
SELECT FirstProductID,'Linked' from @ProductRelation
UNION
SELECT SecondProductID ,'Linked' FROM @ProductRelation
以上查询结果重复ProductID
我想选择不同的ProductID ...如果产品ID之间存在关联,那么它应该显示带有'Linked'的ProductID 如果没有关系,那么ProductID与'Not Linked'
我想要这样的预期结果
ProductID Relation
1 Linked
2 Linked
3 Linked
4 Linked
5 Linked
6 Linked
7 Not Linked
8 Not Linked
9 Not Linked
10 Not Linked
答案 0 :(得分:1)
试试这个:
SELECT
P.ProductID,
CASE WHEN COUNT(R.FirstProductID) > 0
THEN 'Linked'
ELSE 'Not Linked'
END Relation
FROM Product P
LEFT JOIN ProductRelation R
ON P.ProductID = R.FirstProductID
OR P.ProductID = R.SecondProductID
GROUP BY P.ProductID
答案 1 :(得分:1)
select P.ProductID
,isnull(L.relation,'Not Linked') as relation
from @Product P
left outer join (select U.ProductID, cast('Linked' as varchar(max)) as relation
from @ProductRelation
unpivot (ProductID for prod in (FirstProductID,SecondProductID))U
group by U.ProductID
)L
on L.ProductID = P.ProductID
答案 2 :(得分:0)
您可以在SQL Server中使用左连接和CASE WHEN
SELECT DISTINCT
ProductID,
CASE WHEN @ProductRelation.FirstProductId IS NULL THEN 'Not Linked' ELSE 'Linked' END [Status]
FROM @Product
LEFT JOIN @ProductRelation ON @Product.ProductID = @ProductRelation.FirstProductId
RIGHT JOIN @ProductRelation ON @Product.ProductID = @ProductRelation.SecondProductId