如果属于所有类别,我如何获得特定产品?

时间:2013-03-17 11:16:54

标签: sql sql-server sql-server-2008

我有以下表格

CATEGORY TABLE

╔════╦═══════╗
║ ID ║ NAME  ║
╠════╬═══════╣
║  1 ║ cat 1 ║
║  2 ║ cat 2 ║
║  3 ║ cat 3 ║
╚════╩═══════╝

产品表

╔════╦════════════╦═════════════╗
║ ID ║ CATEGORYID ║ PRODUCTNAME ║
╠════╬════════════╬═════════════╣
║  1 ║          1 ║ product1    ║
║  2 ║          1 ║ product2    ║
║  3 ║          1 ║ product3    ║
║  4 ║          2 ║ product1    ║
║  5 ║          2 ║ product2    ║
║  6 ║          3 ║ product1    ║
║  7 ║          3 ║ product3    ║
╚════╩════════════╩═════════════╝

OUTPUT表

╔════╦════════════╦═════════════╗
║ ID ║ CATEGORYID ║ PRODUCTNAME ║
╠════╬════════════╬═════════════╣
║  1 ║          1 ║ product1    ║
║  4 ║          2 ║ product1    ║
║  6 ║          3 ║ product1    ║
╚════╩════════════╩═════════════╝

在每个类别中都有一个产品名称“product1”,因此我需要一个可用于所有类别的产品列表。

任何人都可以帮我解决SQL Server T-SQL查询的问题吗?

4 个答案:

答案 0 :(得分:4)

SELECT  a.*
FROM    Product a
        INNER JOIN
        (
            SELECT  ProductName
            FROM    Product
            GROUP   BY ProductName
            HAVING  COUNT(DISTINCT CategoryID) = (SELECT COUNT(*) FROM Category)
        ) b ON a.ProductName = b.ProductName

输出

╔════╦════════════╦═════════════╗
║ ID ║ CATEGORYID ║ PRODUCTNAME ║
╠════╬════════════╬═════════════╣
║  1 ║          1 ║ product1    ║
║  4 ║          2 ║ product1    ║
║  6 ║          3 ║ product1    ║
╚════╩════════════╩═════════════╝

答案 1 :(得分:1)

尝试:

with cte as
(select p.*, count(*) over (partition by PRODUCTNAME) cats
 from product p)
select ID, CATEGORYID, PRODUCTNAME
from cte p
join (select count(*) totcats from category) c
on p.cats=c.totcats

答案 2 :(得分:0)

NOT EXISTSEXCEPT运营商的选项

SELECT *
FROM dbo.Product p
WHERE NOT EXISTS (
                  SELECT p3.[ID]
                  FROM dbo.Category p3                  
                  EXCEPT
                  SELECT p2.[CAtegoryID]
                  FROM dbo.Product p2
                  WHERE p2.[productName] = p.[productName]                        
                  ) 

SQLFiddle上的演示

为了提高性能,请使用此索引

CREATE INDEX ix_ID_Category ON Category(ID)

答案 3 :(得分:0)

通过EXISTS

SELECT  a.*
FROM    Product a
where exists
        (
            SELECT  1
            FROM    Product
            where a.ProductName = Product.ProductName
            HAVING  COUNT(DISTINCT CategoryID) = (SELECT COUNT(*) FROM Category)
        )