日期:2014-05-17 浏览次数:20417 次
--> 测试数据:#tb
IF OBJECT_ID('TEMPDB.DBO.#tb') IS NOT NULL DROP TABLE #tb
GO
CREATE TABLE #tb([CustomerID] INT,[ProductCode] VARCHAR(1))
INSERT #tb
SELECT 1,'A' UNION ALL
SELECT 1,'B' UNION ALL
SELECT 2,'A' UNION ALL
SELECT 2,'B' UNION ALL
SELECT 2,'D' UNION ALL
SELECT 3,'A' UNION ALL
SELECT 3,'B' UNION ALL
SELECT 3,'D' UNION ALL
SELECT 3,'A' UNION ALL
SELECT 3,'D' UNION ALL
SELECT 4,'A' UNION ALL
SELECT 4,'B' UNION ALL
SELECT 4,'C' UNION ALL
SELECT 5,'A' UNION ALL
SELECT 5,'B' UNION ALL
SELECT 5,'A' UNION ALL
SELECT 5,'B' UNION ALL
SELECT 5,'C' UNION ALL
SELECT 5,'D' UNION ALL
SELECT 6,'A' UNION ALL
SELECT 6,'A' UNION ALL
SELECT 6,'D' UNION ALL
SELECT 6,'E' UNION ALL
SELECT 7,'B' UNION ALL
SELECT 7,'B' UNION ALL
SELECT 7,'D' UNION ALL
SELECT 7,'E'
--------------开始查询--------------------------
SELECT CustomerID
FROM #tb
WHERE ProductCode IN ('A', 'B')
GROUP BY CustomerID
HAVING COUNT(DISTINCT ProductCode) = 2
EXCEPT
SELECT CustomerID
FROM #tb
WHERE ProductCode = 'C'
----------------结果----------------------------
/*
* CustomerID
1
2
3
*/
SELECT CustomerID
FROM [t]
WHERE ProductCode IN ('A','B')
GROUP BY CustomerID