使用多个总和优化查询?
Optimizing query with multiple sums?
我有 table products
:
+----------+-----------+----------+---------+
|family_id |shopper_id |product_id|quantity |
+----------+-----------+----------+---------+
|A |1 |Kit Kat |10 |
|A |1 |Kit Kat |5 |
|A |1 |Snickers |9 |
|A |2 |Kit Kat |7 |
|B |3 |Kit Kat |2 |
+----------+---------- +----------+---------+
对于每个产品,我要计算 2 个总数:
- 每个购物者的总数量
- 每个家庭的总数量。同一家庭中所有购物者的总数量。
最后的 table 应该是这样的:
+----------+----------+-------------------------+-----------------------+
|shopper_id|product_id|total_quantity_shopper |total_quantity_family |
+----------+----------+-------------------------+-----------------------+
|1 |Kit Kat | 15 | 22 |
|1 |Snickers | 9 | 9 |
|2 |Kit Kat | 7 | 22 |
|3 |Kit Kat | 2 | 2 |
+----------+----------+-------------------------|-----------------------|
这是我的查询:
SELECT
distinct shopper_id,
product_id,
sum(quantity) OVER (PARTITION BY shopper_id, product_id) as total_quantity_shopper,
sum(quantity) OVER (PARTITION BY family_id, product_id) as total_quantity_family
FROM
products;
但是从查询计划来看,它看起来非常低效(我认为)。我怎样才能改进上面的查询?
我认为家庭是购物者的等级制度。所以,我建议 group by
和 window 函数:
select family_id, shopper_id, product_id,
sum(quantity) as total_quantity_shopper,
sum(sum(quantity)) over (partition by family_id, product_id) as total_quantity_family
from products
group by family_id, shopper_id, product_id
我有 table products
:
+----------+-----------+----------+---------+
|family_id |shopper_id |product_id|quantity |
+----------+-----------+----------+---------+
|A |1 |Kit Kat |10 |
|A |1 |Kit Kat |5 |
|A |1 |Snickers |9 |
|A |2 |Kit Kat |7 |
|B |3 |Kit Kat |2 |
+----------+---------- +----------+---------+
对于每个产品,我要计算 2 个总数:
- 每个购物者的总数量
- 每个家庭的总数量。同一家庭中所有购物者的总数量。
最后的 table 应该是这样的:
+----------+----------+-------------------------+-----------------------+
|shopper_id|product_id|total_quantity_shopper |total_quantity_family |
+----------+----------+-------------------------+-----------------------+
|1 |Kit Kat | 15 | 22 |
|1 |Snickers | 9 | 9 |
|2 |Kit Kat | 7 | 22 |
|3 |Kit Kat | 2 | 2 |
+----------+----------+-------------------------|-----------------------|
这是我的查询:
SELECT
distinct shopper_id,
product_id,
sum(quantity) OVER (PARTITION BY shopper_id, product_id) as total_quantity_shopper,
sum(quantity) OVER (PARTITION BY family_id, product_id) as total_quantity_family
FROM
products;
但是从查询计划来看,它看起来非常低效(我认为)。我怎样才能改进上面的查询?
我认为家庭是购物者的等级制度。所以,我建议 group by
和 window 函数:
select family_id, shopper_id, product_id,
sum(quantity) as total_quantity_shopper,
sum(sum(quantity)) over (partition by family_id, product_id) as total_quantity_family
from products
group by family_id, shopper_id, product_id