用单个表选择填充空白

时间:2020-10-09 09:26:05

标签: sql postgresql

给出下表:

table1:

user_id | date_created | product
1         2020-10-02     1
1         2020-10-08     1
1         2020-10-08     1
1         2020-10-09     1

然后选择:

select to_char(date_created, 'Dy') as day,
    count(product)
from table1
where user_id = 1
    and date_created >= now() - interval '10 days'
group by day

它产生以下输出:

 day | count
-----+-------
 Fri |     1
 Thu |     2
 Fri |     1
(3 rows)

在没有products的日子里如何填充空白,以便显示0?像这样:

day  | count
-----+-------
 Fri |     1
 Sat |     0
 Sun |     0
 Mon |     0
 Tue |     0
 Wed |     0
 Thu |     2
 Fri |     1
(8 rows)

使用left outer联接来联接两个表是可行的,但是我在这里使用单个表。我可以在前端进行修饰,但是能够在SQL中处理它会很好。

我很乐意发表评论!

谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用generate_series()

select to_char(d.dt, 'Dy') as day,
       count(t.product)
from generate_series(current_date - 10, current_date, interval '1 day') as d(dt)
  left join table1 t 
         on t.user_id = 1 
        and t.date_created = d.dt::date
group by day