我是SQL的初学者,我遇到了需要帮助的查询。 我有两个以下架构:
我想找到只购买一种商品的客户,这意味着,对于相同的cID,它只能与贸易元组中的相同商品ID配对。
例如:
+----------+-------+
| cID |goodsID|
+----------+-------+
| 1000 | 1 |
| 1000 | 1 |
| 1000 | 1 |
| 1001 | 2 |
| 1001 | 3 |
| 1002 | 4 |
+----------+-------+
输出应为:
+----------+
| cID |
+----------+
| 1000 |
| 1002 |
+----------+
答案 0 :(得分:2)
我认为您需要一个简单的查询:
SELECT CID
FROM yourTable
GROUP BY CID
HAVING COUNT(DISTINCT goodsID) = 1;
答案 1 :(得分:1)
SELECT cID, count(goodsID)
FROM (
SELECT DISTINCT cID, goodsID
FROM table1
) as T
GROUP BY cID
HAVING count(goodsID) = 1