场景
订单表 t_order 有如下数据:
字段分别为, 销售订单号、 订货数量
发货表 t_order_delivery 有如下数据:
字段分别为, 销售订单号、 发货数量
问题
问题1:查询部分发货的 销售订单号数据 ?
分析: 一个订单可能分为多次发货,如果想要获取到一个订单到底发了多少货,就需要对发货单进行聚合。
聚合查询发货单的全部发货数量之和,以及订单的订货数量结果
然后再利用子查询 比较二者的大小关系
先把子查询写出来
SELECT
ANY_VALUE (line.sales_order_id) AS sales_order_id,
SUM(line.order_quantity) AS order_quantity,
SUM(p.delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_order_line line
LEFT JOIN
(SELECT
sales_order_id,
SUM(delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_orderdelivery_position
GROUP BY sales_order_id) AS p
ON line.sales_order_id = p.sales_order_id
GROUP BY line.sales_order_id
再写外层判断条件的查询:
SELECT
*
FROM
(SELECT
ANY_VALUE (line.sales_order_id) AS sales_order_id,
SUM(line.order_quantity) AS order_quantity,
SUM(p.delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_order_line line
LEFT JOIN
(SELECT
sales_order_id,
SUM(delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_orderdelivery_position
GROUP BY sales_order_id) AS p
ON line.sales_order_id = p.sales_order_id
GROUP BY line.sales_order_id) t
WHERE t.order_quantity >= t.delivered_quantity
AND t.delivered_quantity >= 0
整体的思路就是:
利用子查询先分组聚合数据,之后再利用子查询处理分组聚合后的条件查询。
问题2:查询全部发货的 销售订单号数据 ?
SELECT
*
FROM
(SELECT
ANY_VALUE (line.sales_order_id) AS sales_order_id,
SUM(line.order_quantity) AS order_quantity,
SUM(p.delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_order_line line
LEFT JOIN
(SELECT
sales_order_id,
SUM(delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_orderdelivery_position
GROUP BY sales_order_id) AS p
ON line.sales_order_id = p.sales_order_id
GROUP BY line.sales_order_id) t
WHERE t.order_quantity = t.delivered_quantity
问题3:查询未发货的 销售订单号数据 ?
SELECT
*
FROM
(SELECT
ANY_VALUE (line.sales_order_id) AS sales_order_id,
SUM(line.order_quantity) AS order_quantity,
SUM(p.delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_order_line line
LEFT JOIN
(SELECT
sales_order_id,
SUM(delivered_quantity) AS delivered_quantity
FROM
t_ph_ibmp_orderdelivery_position
GROUP BY sales_order_id) AS p
ON line.sales_order_id = p.sales_order_id
GROUP BY line.sales_order_id) t
WHERE t.delivered_quantity = 0
OR t.delivered_quantity IS NULL