我正在创建一个循环通过下表创建报告的过程:
INSERT INTO temp_data
SELECT val_year, val_name, Group_A, Group_B, Group_C, SUM(product_count) AS in_stock
FROM all_products
GROUP BY val_year, val_name, Group_A, Group_B, Group_C;
Resulting rows:
1: 2014, product_a, food, hot, delicious, 50
2: 2014, product_a, food, hot, fast, 30
3: 2014, product_a, food, cold, delicious, 10
4: 2014, product_a, drinks, hot, delicious, 20
5: 2014, product_a, drinks, cold, delicious, 40
6: 2014, product_a, drinks, cold, fast, 60
7: 2014, product_b, food, hot, delicious, 70
... etc.
表all_products以前是通过各种UNION ALL查询等创建的。
我现在需要向上级报告这些结果,但表格看起来有“缺失”值。我需要重建该表,以便显示缺少值为零的组。
我需要以特定模式显示所有值,此示例将是我想要的显示:
Rows:
1: 2014, product_a, food, hot, delicious, 50
2: 2014, product_a, food, hot, fast, 30
3: 2014, product_a, food, cold, delicious, 10
4: 2014, product_a, food, cold, fast, 0
5: 2014, product_a, drinks, hot, delicious, 20
6: 2014, product_a, drinks, hot, fast, 0
7: 2014, product_a, drinks, cold, delicious, 40
8: 2014, product_a, drinks, cold, fast, 60
9: 2014, product_b, food, hot, delicious, 70
... etc.
注意第4行和第6行已经填写,以显示没有库存的产品的零值。
是否有任何简单(快速)的方法来填补缺失的行?我能想到的只有200多行FOR LOOP,它通过当前组,检查组更改并在组更改时添加缺少的组。这种方法感觉有点不专业。
答案 0 :(得分:4)
您可以先生成所有行(使用cross join
)然后输入值来执行此操作:
select y.val_year, g.val_name, g.Group_A, g.Group_B, g.Group_C,
coalesce(in_stock, 0) as in_stock
from (select distinct val_year from temp_data) y cross join
(select distinct val_name, Group_A, Group_B, Group_C from temp_data) g left join
temp_data d
on d.val_year = y.val_year and
d.val_name = g.val_name and
d.Group_A = g.Group_A and
d.Group_B = g.Group_B and
d.Group_C = g.Group_C;
您也可以直接在all_products
上执行此操作。例如,您可以将CTE添加到上述查询中:
with temp_data as (
SELECT val_year, val_name, Group_A, Group_B, Group_C, SUM(product_count) AS in_stock
FROM all_products
GROUP BY val_year, val_name, Group_A, Group_B, Group_C
)