如何选择未定义的行?像第2行有未定义的第3天,第3行有未定义的第1天。我希望它们在结果集中为0。
+----+-----+-------+
| id | day | count |
+----+-----+-------+
| 1 | 1 | 262 |
| 1 | 2 | 685 |
| 1 | 3 | 984 |
| 2 | 1 | 692 |
| 2 | 2 | 962 |
| 3 | 2 | 355 |
| 3 | 3 | 741 |
+----+-----+-------+
编辑:
我想从第1天,第2天和第3天(不是整个表格)中选择count
,然后在未定义的日期显示0。
答案 0 :(得分:0)
id
值。 day
,您似乎只需要1,2和3。因此,我们只能使用UNION ALL
直接考虑这些值。CROSS JOIN
获得所有可能的组合。LEFT JOIN
从all_combinations
表到id
和day
上的主表。Coalesce()
函数将0值视为计数尝试以下操作:
SELECT all_combinations.id,
all_combinations.day,
COALESCE(t.count, 0) AS count
FROM
(
SELECT ids.id, days.day
FROM
(SELECT DISTINCT id FROM your_table) AS ids
CROSS JOIN
(SELECT 1 AS day UNION ALL SELECT 2 UNION ALL SELECT 3) AS days
) AS all_combinations
LEFT JOIN your_table AS t
ON t.id = all_combinations.id AND
t.day = all_combinations.day
结果:
| id | day | count |
| --- | --- | ----- |
| 1 | 1 | 262 |
| 2 | 1 | 692 |
| 3 | 1 | 0 |
| 1 | 2 | 685 |
| 2 | 2 | 962 |
| 3 | 2 | 355 |
| 1 | 3 | 984 |
| 2 | 3 | 0 |
| 3 | 3 | 741 |