向SQL查询结果添加行

时间:2017-03-30 17:32:30

标签: postgresql

我的Java应用程序中有一个自定义查询,如下所示:

select 
    to_char(search.timestamp,'Mon') as mon, 
    COUNT(DISTINCT(search.ip_address))
from 
    searches 
WHERE 
    searches.city = 1 
group by 1;

应该返回数据库中发生的所有月份,以及每个月内不同IP地址的数量。但是,此时,某些月份没有任何条目,并且SQL查询结果中缺少这些条目。我怎样才能确保所有月份都显示在那里,即使它们的数量是0?

使用它:

select  
    to_char (gs.m,'Mon') as mon,  
    count (distinct search.ip_address) 
from
    generate_series (
          date_trunc('month', current_date - interval '11 month'),
          current_date,
          '1 month'
      ) gs (m)
    left join searches
    on date_trunc('month', search.timestamp) = gs.m AND search.city = 1
group by gs.m 
order by gs.m;

2 个答案:

答案 0 :(得分:1)

像这样(未经测试):

select 
    months.mon
    , COUNT(DISTINCT(searchs.ip_address))
from 
    (select 
        to_char(searches.timestamp,'Mon') as mon
     from 
        searches
     group by 1
    ) months
    left join searches 
    on to_char(searchs.timestamp,'Mon') = months.mon
    and searches.city = 1 
group by 1;

如果你想要那里的岁月,也可以尝试这样的事情(未经测试):

select 
    months.mon
    , COUNT(DISTINCT(searchs.ip_address))
from 
    (select 
        extract(year from searches.timestamp) as yr
        , to_char(searches.timestamp,'Mon') as mon
        , to_char(yr,'9999') || mon yrmon
     from 
        searches
     group by 1
    ) months
    left join searches 
    on to_char(extract(year from searches.timestamp),'9999' || 
        to_char(searchs.timestamp,'Mon') = months.yrmon
    and searches.city = 1 
group by 1;

答案 1 :(得分:1)

select 
    to_char (gs.m,'Mon') as mon, 
    count (distinct(search.ip_address))
from 
    searches
    right join
    generate_series (
        date_trunc('month', current_date - interval '1 year'),
        current_date,
        '1 month'
    ) gs (m) on date_trunc('month', search.timestamp) = gs.m
where searches.city = 1 
group by gs.m
order by gs.m;