SQL查找具有单个出现的引用

时间:2015-06-09 14:14:35

标签: sql group-by subquery aggregate

我正在尝试为以下问题找到纯SQL解决方案:

如果我卖油漆和油漆刷,并记录下这样销售的颜色:

    select OrderNumber, Product, Product_Type, Qty from Sales

+-------------+------------+--------------+-----+
| OrderNumber |  Product   | Product_Type | Qty |
+-------------+------------+--------------+-----+
|        0001 | Red        | Paint        |   1 |
|        0001 | Blue       | Paint        |   2 |
|        0001 | Green      | Paint        |   1 |
|        0001 | Paintbrush | Brush        |   1 |
|        0002 | Green      | Paint        |   1 |
|        0002 | Paintbrush | Brush        |   1 |
|        0003 | Blue       | Paint        |   4 |
|        0003 | Red        | Paint        |   5 |
|        0003 | Paintbrush | Brush        |   1 |
|        0004 | Blue       | Paint        |   2 |
|        0004 | Paintbrush | Brush        |   1 |
|        0005 | Green      | Paint        |   1 |
|        0005 | Paintbrush | Brush        |   1 |
+-------------+------------+--------------+-----+

有没有办法隔离只售出一罐油漆的订单,那罐油漆是绿色的?我想忽略画笔,因为每个订单都包含画笔。因此,从示例数据集中,所需的结果将是#0002和#0005订单,因为在每个订单中,所售油漆罐的总数量为1,并且这些罐子为绿色。

我认为答案可能在于group by子句和一些聚合函数以及可能的子查询。但是,我不确定如何将这些结合起来以获得我需要的结果。

1 个答案:

答案 0 :(得分:5)

首先,过滤掉所有画笔。这可以在where子句中完成。

然后,您需要将每个订单作为一堆记录处理。这可以通过group by OrderNumber, Product_Type来实现,这会将您的表分成订单组。然后,您可以在having子句中过滤这些组,以仅查找其中包含单个已售商品的组。

select OrderNumber
  from Sales
  where Product_Type <> 'Brush'
  group by OrderNumber, Product_Type
  having sum(qty) = 1
     and min(Product) = 'Green'