ADD INSEET to SELECT QUERY for missing values
ADD INSEET to SELECT QUERY for missing values
我有以下简化的table。
|---------------------|------------------|------------------|
| month | customer | value |
|---------------------|------------------|------------------|
| 1 | A | 20 |
|---------------------|------------------|------------------|
| 1 | B | 20 |
|---------------------|------------------|------------------|
| 1 | C | 20 |
|---------------------|------------------|------------------|
| 2 | A | 20 |
|---------------------|------------------|------------------|
| 2 | B | 20 |
|---------------------|------------------|------------------|
如您所见,第 2 个月没有客户 C 的价值。
在这种情况下,我需要以编程方式在我的 select 语句中添加 month='2' customer='C' value='0'
SELECT month, customer, value FROM mytable
我的真实 table 中有更多行,但每个月的最终结果需要是相同的客户列表。
非常感谢任何帮助。
使用 cross join
生成行,使用 left join
引入值:
select m.month, c.customer, coalesce(t.value, 0) as value
from (select distinct month from t) m cross join
(select distinct customer from t) c left join
t
on t.month = m.month and t.customer = c.customer;
注意:如果您有月份或客户的其他来源,那么这些来源可能比使用 count(distinct)
更快。
我有以下简化的table。
|---------------------|------------------|------------------|
| month | customer | value |
|---------------------|------------------|------------------|
| 1 | A | 20 |
|---------------------|------------------|------------------|
| 1 | B | 20 |
|---------------------|------------------|------------------|
| 1 | C | 20 |
|---------------------|------------------|------------------|
| 2 | A | 20 |
|---------------------|------------------|------------------|
| 2 | B | 20 |
|---------------------|------------------|------------------|
如您所见,第 2 个月没有客户 C 的价值。
在这种情况下,我需要以编程方式在我的 select 语句中添加 month='2' customer='C' value='0'
SELECT month, customer, value FROM mytable
我的真实 table 中有更多行,但每个月的最终结果需要是相同的客户列表。
非常感谢任何帮助。
使用 cross join
生成行,使用 left join
引入值:
select m.month, c.customer, coalesce(t.value, 0) as value
from (select distinct month from t) m cross join
(select distinct customer from t) c left join
t
on t.month = m.month and t.customer = c.customer;
注意:如果您有月份或客户的其他来源,那么这些来源可能比使用 count(distinct)
更快。