通过用 0s 填充 table,确保 Column1 的每个不同值都有一行包含 Column2 的每个不同值 - postgresql
Make sure every distinct value of Column1 has a row with every distinct value of Column2, by populating a table with 0s - postgresql
这是我编造的一个粗略示例,用于说明我想要实现的目标:
表 1:
| Shop | Product | QuantityInStock |
| a | Prod1 | 13 |
| a | Prod3 | 13 |
| b | Prod2 | 13 |
| b | Prod3 | 13 |
| b | Prod4 | 13 |
表 1 变为:
| Shop | Product | QuantityInStock |
| a | Prod1 | 13 |
| a | Prod2 | 0 | -- new
| a | Prod3 | 13 |
| a | Prod4 | 0 | -- new
| b | Prod1 | 0 | -- new
| b | Prod2 | 13 |
| b | Prod3 | 13 |
| b | Prod4 | 13 |
在这个例子中,我想代表每个 Shop/Product 组合
每个商店 {a,b} 与每个产品 {Prod1、Prod2、Prod3、Prod4} 有一行
QuantityInStock=13 没有意义,我只是想要一个占位符数字:)
使用日历table交叉连接方法:
SELECT s.Shop, p.Product, COALESCE(t1.QuantityInStock, 0) AS QuantityInStock
FROM (SELECT DISTINCT Shop FROM table1) s
CROSS JOIN (SELECT DISTINCT Product FROM table1) p
LEFT JOIN table1 t1
ON t1.Shop = s.Shop AND
t1.Product = p.Product
ORDER BY
s.Shop,
p.Product;
这里的想法是通过交叉连接生成包含所有 shop/product 组合的中间 table。然后,我们离开 join this to table1
。 不的任何 shop/product 组合在实际 table 中具有匹配项,则分配的库存数量为零。
这是我编造的一个粗略示例,用于说明我想要实现的目标:
表 1:
| Shop | Product | QuantityInStock |
| a | Prod1 | 13 |
| a | Prod3 | 13 |
| b | Prod2 | 13 |
| b | Prod3 | 13 |
| b | Prod4 | 13 |
表 1 变为:
| Shop | Product | QuantityInStock |
| a | Prod1 | 13 |
| a | Prod2 | 0 | -- new
| a | Prod3 | 13 |
| a | Prod4 | 0 | -- new
| b | Prod1 | 0 | -- new
| b | Prod2 | 13 |
| b | Prod3 | 13 |
| b | Prod4 | 13 |
在这个例子中,我想代表每个 Shop/Product 组合
每个商店 {a,b} 与每个产品 {Prod1、Prod2、Prod3、Prod4} 有一行
QuantityInStock=13 没有意义,我只是想要一个占位符数字:)
使用日历table交叉连接方法:
SELECT s.Shop, p.Product, COALESCE(t1.QuantityInStock, 0) AS QuantityInStock
FROM (SELECT DISTINCT Shop FROM table1) s
CROSS JOIN (SELECT DISTINCT Product FROM table1) p
LEFT JOIN table1 t1
ON t1.Shop = s.Shop AND
t1.Product = p.Product
ORDER BY
s.Shop,
p.Product;
这里的想法是通过交叉连接生成包含所有 shop/product 组合的中间 table。然后,我们离开 join this to table1
。 不的任何 shop/product 组合在实际 table 中具有匹配项,则分配的库存数量为零。