SQL 查找单次出现的参考文献
SQL find references with single occurrences
我正在尝试为以下问题找到一个纯粹的 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 子句和一些聚合函数以及可能的子查询。但是,我不确定如何将这些结合起来以获得我需要的结果。
首先,过滤掉所有画笔。这可以在 where
子句中完成。
然后您需要将每个订单作为一堆记录进行处理。这可以通过 group by OrderNumber, Product_Type
将您的 table 分成订单组来实现。然后,您可以在 having
子句中筛选这些组,以仅查找其中包含单个已售商品的组。
select OrderNumber
from Sales
where Product_Type <> 'Brush'
group by OrderNumber, Product_Type
having sum(qty) = 1
and min(Product) = 'Green'
我正在尝试为以下问题找到一个纯粹的 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 子句和一些聚合函数以及可能的子查询。但是,我不确定如何将这些结合起来以获得我需要的结果。
首先,过滤掉所有画笔。这可以在 where
子句中完成。
然后您需要将每个订单作为一堆记录进行处理。这可以通过 group by OrderNumber, Product_Type
将您的 table 分成订单组来实现。然后,您可以在 having
子句中筛选这些组,以仅查找其中包含单个已售商品的组。
select OrderNumber
from Sales
where Product_Type <> 'Brush'
group by OrderNumber, Product_Type
having sum(qty) = 1
and min(Product) = 'Green'