3

我有如下表格

类别表

╔════╦═══════╗
║ 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    ║
╚════╩════════════╩═════════════╝

输出表

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

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

谁能帮助我如何使用 SQL Server T-SQL 查询来做到这一点?

4

4 回答 4

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    ║
╚════╩════════════╩═════════════╝
于 2013-03-17T11:20:15.667 回答
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
于 2013-03-17T12:29:49.793 回答
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)
于 2013-03-17T12:17:57.880 回答
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)
        ) 
于 2013-03-18T18:26:17.457 回答