2010-07-26 48 views
1

包含以下數據:SQL Server 2008中選擇表和作風狀況鑑於這樣 <img src="https://i.imgur.com/6TO87.png" alt="alt text"></p> <p>ProductFacets模型相關的表

ProductId, FacetTypeId 
1, 1 
1, 2 
2, 1 
2, 3 
3, 4 
3, 5 
4, 1 
4, 2 

我希望能夠選擇所有其具有的1和2 一個FacetTypeId產品的結果集應包含ProductIds 1和4

+0

爲什麼/ 2應該不包括在結果集中的1,4? (請注意ProductID,FacetTypeID爲2,1) – 2010-07-26 17:35:57

+0

FacetTypeId必須是1和4(可能有1,4和2的產品怎麼樣) – 2010-07-26 17:44:58

+0

可以把它想象成一個過濾器,我們只希望帶有BOTH FacetTypeId 1和2的產品。 – 2010-07-26 19:02:03

回答

1

這將返回僅包含方面類型1和2的產品的行,並且僅包含那些方面。

SELECT ProductId, 
    COUNT(*) AS FacetCountByProduct, 
    SUM(CASE WHEN FacetTypeId in (1, 2) THEN 1 ELSE 0 END) AS FacetCountSelectedFacets 
FROM ProductFacets 
GROUP BY ProductId 
HAVING COUNT(*) = 2 
    and SUM(CASE WHEN FacetTypeId in (1, 2) THEN 1 ELSE 0 END) = 2 
; 
0
SELECT * FROM Product PROD WHERE PROD.ProductId IN(

SELECT P.ProductId pId FROM ProductFacets AS P 
WHERE P.FacetTypeId = 1 

AND EXISTS 
(
    SELECT * 
    FROM ProductFacets AS P1 
    WHERE P1.FacetTypeid = 2 
     AND P1.ProductId = pId 
) 

AND NOT EXISTS 
(
    SELECT * 
    FROM ProductFacets AS P2 
    WHERE P2.FacetTypeid NOT IN (1,2) 
     AND P2.ProductId = pId 
) 

) 

有畝st是一個更好的方法來解決這個問題,但它是唯一一個我可以想出的

0

只是想到了一個辦法做到這一點:

select distinct ProductId from ProductFacets 
where ProductId in (select ProductId from ProductFacets where FacetTypeId = 1) 
and ProductId in (select ProductId from ProductFacets where FacetTypeId = 2) 
相關問題