【发布时间】:2017-06-05 07:25:35
【问题描述】:
我有一张这样的桌子:
meterId | startDate | endDate |location
meter01 | 2017-05-01 |2017-05-16| locA
meter02 | 2017-05-01 |9999-12-31| locB
meter03 | 2017-01-01 |9999-12-31| locA
meter04 | 2017-01-01 |9999-12-31| locB
我需要返回某个位置在给定月份中的活动天数。查询需要返回: (假设 5 月有 31 天)
location | Month | days |
locA | May-17 | 47 |
locB | May-17 | 62 |
到目前为止我尝试过的是这样的:(请注意,我正在加入另一个不是最佳的表,并在此处显示)
SELECT count(distinct(read_date)) AS days, location from t where EXTRACT(MONTH FROM read_date) = 5 and EXTRACT(YEAR FROM read_date) = 2017
有点接近。然而,它有重复的位置。我还需要上述格式的日期。
@StanislavL 的新编辑
select SUM(sub.intervalEnd - sub.intervalStart +1) as days,
location
from (select
location,
case when effective_start_date> '2017-05-01' then effective_start_date else '2017-05-01' end as intervalStart,
case when effective_end_date< '2017-05-31' then effective_end_date else '2017-05-31' end as intervalEnd
from my_table
where (effective_start_date<='2017-05-01' and effective_end_date>='2017-05-01')
OR (effective_start_date<='2017-05-31' and effective_end_date>='2017-05-31'))sub
group by location
【问题讨论】:
-
5 月 17 日的 locA 计数是从哪里得到的?根据您的数据,计数看起来不正确。
-
@Sumit, 16 + 31 = 47
-
@Sumit 是的,第一个仪表只活跃了 16 天,而其余的仪表则整个月都活跃。
-
表格中的读取日期在哪里?
-
我稍微修改了您的查询,请试试这个。 SELECT count(distinct(read_date)) AS days, to_char(read_date, 'Month')||'-'|| to_char(read_date,'YY')as Month, location from t where EXTRACT(MONTH FROM read_date) = 5 and EXTRACT(YEAR FROM read_date) = 2017 GROUP BY Location, read_date
标签: sql postgresql