PostgreSQL过滤器不完整年份

时间:2019-03-22 09:03:26

标签: postgresql

问题:在某些月份中的记录中缺失。需要过滤掉不完整月份的整个年份。

DATE             VALUE
2018-01-01       123
2018-02-01       123
2018-03-01       123
2018-04-01       123
2018-05-01       123
2018-06-01       123
2018-07-01       123
2018-08-01       123
2018-09-01       123
2018-10-01       123
2018-11-01       123
2018-12-01       123
2019-01-01       123 // Remove.

研究:

CREATE TABLE new_table AS
SELECT * FROM my_table
WHERE ...

问题:

How to get:

DATE             VALUE
2018-01-01       123
2018-02-01       123
2018-03-01       123
2018-04-01       123
2018-05-01       123
2018-06-01       123
2018-07-01       123
2018-08-01       123
2018-09-01       123
2018-10-01       123
2018-11-01       123
2018-12-01       123

1 个答案:

答案 0 :(得分:3)

您可以使用group by语句查找存在所有月份的地址:

select to_char(date, 'yyyy')
from the_table
group by to_char(date, 'yyyy')
having count(distinct to_char(date, 'mm')) = 12;

这只能用于获取您感兴趣的对象:

select *
from the_table
where to_char(date, 'yyyy') in (select to_char(date, 'yyyy')
                                   from the_table
                                   group by to_char(date, 'yyyy')
                                   having count(distinct to_char(date, 'mm')) = 12);

或者使用extract(year from ..)

select extract(year from date)
from the_table
group by extract(year from date)
having count(*) = 12;

在线示例:https://rextester.com/LKF6618