列
date |count|ip
2014-05-14 11:21:00 |2 | 222.222.222.22
2014-05-14 11:22:00 |4 | 232.232.232.23
2014-05-14 11:24:00 |1 | 222.222.222.22
this is working fine for me但是这个解决方案为我提供了系列值null,但我需要值0而不是null
在当前查询中,如果没有填充缺失序列,我就无法得到确切的序列
当前查询:
SELECT sum(date),minute
FROM generate_series('2014-05-14 0:00:00'::timestamp, '2014-05-14 23:59:59',
'1 minute') AS minutes(minute)
LEFT JOIN table ON minute=date_trunc('minute',table.date)
where switch_ip='232.232.232.23'
GROUP BY minute
当前输出:
2014-05-14 11:22:00 |4
必需输出:
1)如果在ip = 232.232.232.23且日期> ='2014-05-14 00:00:00'且日期< ='2014-05-14 23:59:59'
2014-05-14 11:21:00 | 0
2014-05-14 11:22:00 | 4
2014-05-14 11:23:00 | 0
2)如果在ip 222.222.222.22和日期> ='2014-05-14 00:00:00'和日期< ='2014-05-14 23:59:59'
2014-05-14 11:21:00 | 2
2014-05-14 11:22:00 | 0
2014-05-14 11:23:00 | 0
2014-05-14 11:24:00 | 1
3)如果在日期> ='2014-05-14 00:00:00'和日期< ='2014-05-14 23:59:59'
2014-05-14 11:21:00 | 2
2014-05-14 11:22:00 | 4
2014-05-14 11:23:00 | 0
2014-05-14 11:24:00 | 1
答案 0 :(得分:3)
通过将ip条件放在where子句中,您将外部联接转换为内部联接。将其移至连接条件
select coalesce(sum("count"), 0), minute
from
generate_series(
'2014-05-14 0:00:00'::timestamp,
'2014-05-14 23:59:59',
'1 minute'
) minutes(minute)
left join
t on
minutes.minute = date_trunc('minute', t.date)
and
ip = '232.232.232.23'
group by minute
order by minute
http://sqlfiddle.com/#!15/31483/5
将时间戳作为逗号分隔的字符串替换
select coalesce(sum("count"), 0), minute
通过
select
coalesce(sum("count"), 0),
to_char(minute, 'YYYY,MM,DD,HH24,MI') as minute