SQL选择仅销售一种产品的经销商

时间:2014-06-24 15:29:54

标签: sql

我正在尝试为以下

创建SQL语句

我想要完成的是一个只显示仅销售A产品的ID的输出。因此,ID 5546将被排除,因为他们已售出B产品。谢谢!

+------------+---------+
|            |         |
+------------+---------+
| Dealercode | Product |
| 5546       | A       |
| 5546       | B       |
| 2214       | A       |
| 3654       | A       |
|            |         |
| Output     |         |
| Dealercode | Product |
| 2214       | A       |
| 3654       | A       |
+------------+---------+

1 个答案:

答案 0 :(得分:2)

这几乎是一个基本的聚合查询,但有一个转折:

select dealercode, max(product) as product
from table t
group by dealercode
having count(distinct product) = 1;

如果只有一种产品,则max(product)将成为该产品。 having条款仅为每位经销商保证一种产品(假设product永远不会NULL)。

如果您正在学习SQL,则应该学习group byhaving。这些是该语言的基本部分。

编辑:

啊,"只卖了A产品" (我想我读过#34;只卖了一个产品")。然后使用:

select dealercode, max(product) as product
from table t
group by dealercode
having min(product) = max(product) and min(product) = 'A';
相关问题