需要帮助构建单个表的SQL查询

时间:2011-05-17 17:41:58

标签: sql

我有一个包含以下字段的表:

ID 
brandID
productID

我想知道有多少不同的brandID在此表中至少有一条记录,同时包含productID 1和productID 2.例如:

ID|brandID|productID
1 | 1     | 1
2 | 1     | 2
3 | 1     | 2
4 | 2     | 2
5 | 3     | 1
6 | 3     | 1

在上面的示例表中,只有brandID 1有一行包含productID 1和productID 2. brandIDs 2和3只有一个产品或另一个。

如何构建查询以获取包含productID 1和2的不同brandID的计数?

6 个答案:

答案 0 :(得分:3)

select COUNT(*)
from (
    select brandID
    from MyTable
    where productID in (1, 2)
    group by brandID
    having count(distinct productID) = 2
) a

答案 1 :(得分:0)

如果你的表名为t,它应该是这样的:

select count(distinct t1.brandID)
from t t1, t t2
where t1.brandID = t2.brandID and t1.productID = 1 and t2.productID = 2

答案 2 :(得分:0)

使用子选项与brandID获得不同的productID=1,然后获取计数:

SELECT COUNT(DISTINCT(brandID)) FROM tbl WHERE brandID IN (SELECT DISTINCT brandID FROM tbl WHERE productID=1) AND productID=2;

答案 3 :(得分:0)

select distinct brandid, count(1) from sampletable 
 where productid in (1, 2) 
 group by brandid having count(1) > 1

答案 4 :(得分:0)

用于SQL Server 2005及更高版本:

DECLARE @t TABLE(ID INT, brandID INT, productID INT)
INSERT INTO @t
SELECT 1, 1, 1 UNION ALL 
SELECT 2, 1, 2 UNION ALL 
SELECT 3, 1, 2 UNION ALL 
SELECT 4, 2, 2 UNION ALL 
SELECT 5, 3, 1 UNION ALL 
SELECT 6, 3, 2 UNION ALL 
SELECT 7, 3, 4 UNION ALL 
SELECT 8, 3, 5

SELECT * FROM @t    

;WITH cte
AS
(
    SELECT  ROW_NUMBER() OVER(PARTITION BY brandID ORDER BY productID) AS RN, *
    FROM    @t
    WHERE   productID IN (1,2)
)
SELECT  DISTINCT brandID
FROM    cte
WHERE   RN > 1

答案 5 :(得分:0)

这就是我要做的事情:

select distinct brandid from t
where brandid in (select distinct brandid from t where productid = 1)
and brandid in  (select distinct brandid from t where productid = 2)