表t如下所示:
+-----+------+-------+
| key | week | value |
+-----+------+-------+
| 1 | 1 | 10 |
| 1 | 2 | 20 |
| 2 | 1 | 100 |
| 2 | 2 | 200 |
| 2 | 3 | 300 |
+-----+------+-------+
key
2的value
1、2和3存在week
,
但key
1和value
1和2仅具有week
我如何编写查询以添加key
1行和缺失的week
3行,且默认value
为0,所以结果表如下所示:< / p>
+-----+------+-------+
| key | week | value |
+-----+------+-------+
| 1 | 1 | 10 |
| 1 | 2 | 20 |
| 1 | 3 | 0 |
| 2 | 1 | 100 |
| 2 | 2 | 200 |
| 2 | 3 | 300 |
+-----+------+-------+
我尝试了交叉联接和完全外部联接(在不同的星期列表中),但不知何故未能达成理想的解决方案
答案 0 :(得分:0)
使用cross join
生成所有行,然后使用left join
引入值:
select k.key, w.week, coalesce(t.value, 0) as value
from (select distinct key from t) k cross join
(select distinct week from t) w left join
t
on t.key = k.key and t.week = w.week
order by k.key, w.week;
这使用原始表作为密钥和星期的来源。如果您还有其他具有此信息的表,则可以使用它。