向数据库表中不存在的数据中的查询添加新行

时间:2018-06-22 21:58:09

标签: sql postgresql

我有以下示例表:

+----------+------+-------+
|   DATE   | NAME | HOURS |
+----------+------+-------+
| 2018-5-3 | JOHN |   8   |
+----------+------+-------+
| 2018-5-9 | JOHN |   5   |
+----------+------+-------+

如何生成查询以将新行填充到现有数据中,例如样本查询结果:

+-----------+------+-------+
|   DATE    | NAME | HOURS |
+-----------+------+-------+
| 2018-5-1  | JOHN |   0   |
+-----------+------+-------+
| 2018-5-2  | JOHN |   0   |
+-----------+------+-------+
| 2018-5-3  | JOHN |   8   |
+-----------+------+-------+
| 2018-5-4  | JOHN |   0   |
+-----------+------+-------+
| 2018-5-5  | JOHN |   0   |
+-----------+------+-------+
| 2018-5-6  | JOHN |   0   |
+-----------+------+-------+
| 2018-5-7  | JOHN |   0   |
+-----------+------+-------+
| 2018-5-8  | JOHN |   0   |
+-----------+------+-------+
| 2018-5-9  | JOHN |   5   |
+-----------+------+-------+
| 2018-5-10 | JOHN |   0   |
+-----------+------+-------+

检查我是否在HOURS列中添加了0,因为JOHN在指定日期(仅在2018-5-3和2018-5-8中)没有显示小时数。我目前正在尝试获得此结果。这只是我需要处理的大表的开始,因此我需要为每个用户生成此固定值。我正在尝试将左/右联接与以前生成的日期一起使用,但是没有用。

您能给我建议最好的方法吗?谢谢。

1 个答案:

答案 0 :(得分:0)

使用generate_series()left join

select g.dte, t.name, coalesce(t.hours, 0) as hours
from generate_series('2018-05-01'::date, '2018-05-10'::date, interval '1 day') g(dte) left join
     t 
     on g.dte = t.date;

对于多个用户,您需要为所有用户生成所有行,然后生成left join

select g.dte, n.name, coalesce(t.hours, 0) as hours
from generate_series('2018-05-01'::date, '2018-05-10'::date, interval '1 day'
                    ) g(dte) cross join
     (select distinct name from t) n left join
     t 
     on g.dte = t.date and n.name = t.name;