0

我正在使用filled_months填充空白月份和按月分组数据。问题是我似乎无法让它查询部分月份(例如2016-09-01至2016-09-15),它总是计算整个月份。有人能指引我朝着正确的方向吗?如何让generate_series在一个月的一段时间内工作?

with filled_months AS 
    (SELECT 
    month, 
      0 AS blank_count 
    FROM generate_series(date_trunc('month',date('2016-09-01')), date_trunc('month',date('2016-09-15')), '1 month') AS 
    month) 
SELECT to_char(mnth.month, 'YYYY Mon') AS month_year, 
     count(distinct places.id) 
FROM filled_months mnth 
left outer join restaurants 
    ON date_trunc('month', restaurants.created_at) = mnth.month 
left outer join places 
    ON restaurants.places_id = places.id 
WHERE places.id IS NULL OR restaurants.id IS NULL 
GROUP BY mnth.month 
ORDER BY mnth.month 
+3

问题不明确。 –

回答

0

如果我正确理解你的困惑,我认为你甚至不需要在这里生成系列。我想,您可以在WHERE子句中使用between获得通过,并让SQL分组处理其余部分:

SELECT 
    to_char(r.created_at, 'YYYY Mon') AS month, 
    count(distinct p.id) 
FROM 
    restaurants r 
    left join places p ON r.places_id = p.id 
WHERE 
    r.created_at between '2016-09-01' and '2016-09-15' 
GROUP BY month 
ORDER BY month 

我的日期测试了三个纪录,16年9月1日,16年9月15日和9/30/16,并计算了两个。当我将范围扩大到9/30时,它正确地给了三个。

免责声明:我不明白这是什么意思:

places.id IS NULL OR restaurants.id IS NULL 

如果这行不通,那么也许你可以将某些示例数据添加到您的问题,具有一定的预期结果一起。

相关问题