我有两个日期,我想在日期日期之间获取数据,如果某个日期在db中没有条目,那么它带有zero
计数,我就有mytable,其中{{1} }列。
我尝试过:
id, createddate
此查询不会向我返回日期为select COALESCE(to_char(createddate, 'YYYY-MM-DD'), '0') as date,
count(id) as totalno
from mytable
where (createddate >= '2017-07-13 00:00:00'
and createddate <= '2018-07-13 23:59:59')
group by to_char(createddate, 'YYYY-MM-DD'),
date_part('day', createddate)
的日期数据,该数据在db中没有条目。
我们可以看到日期0
并没有包含15,16,18,22,23
计数。
请帮帮我。
答案 0 :(得分:0)
您可以创建一个理货日期表,然后计算所有日期。即:
with dates ("date") as
(
select '2017-07-13'::date + i
from generate_series(0, '2018-07-13'::date - '2017-07-13'::date) v(i)
)
select "date", count(myTable.id)
from dates
left join myTable on dates."date" = myTable.createdDate
group by dates."date";
注意:也可能是这样:
with dates as
(
select "date"
from generate_series('2017-07-13'::date-1, '2018-07-13'::date,'1 day') v("date")
)
...