如何在PostgreSQL中获得唯一的日期范围?

时间:2018-12-14 04:52:51

标签: postgresql

这是我的数据行:

       start_dte        |        end_dte
------------------------+------------------------
 2018-08-01 00:00:00+00 | 2018-08-05 00:00:00+00
 2018-08-03 00:00:00+00 | 2018-08-05 00:00:00+00
 2018-08-09 00:00:00+00 | 2018-08-10 00:00:00+00
(3 rows)

我想得到这样的结果:

  [
    '2018-08-01',
    '2018-08-02',
    '2018-08-03',
    '2018-08-04',
    '2018-08-05',
    '2018-08-09',
    '2018-08-10',
  ]

如何使用SQL执行此操作?谢谢。

3 个答案:

答案 0 :(得分:1)

这可能是解决方案:

select 
  distinct generate_series(start_date, end_date, '1 day'::interval)::date 
from 
  my_table
order by 
  generate_series asc;

输出:

      generate_series  
 ------------------------  
"2018-08-01"  
"2018-08-02"  
"2018-08-03"  
"2018-08-04"  
"2018-08-05"  
"2018-08-09"  
"2018-08-10"  

答案 1 :(得分:0)

我找到了一种方法,但是不知道这是否是最好的方法。

这是我的解决方法:

for(let i = 0; i < myArray.length; i++){
    myArray[i].addEventListener("click", function(){myFunction(i);});
}

输出:

select 
  distinct generate_series 
from 
  results, 
  generate_series(results.start_dte, results.end_dte, '1 day'::interval) 
order by generate_series asc;

答案 2 :(得分:0)

您可以使用generate_series构造一系列日期,然后从该系列中清楚地选择主表中开始日期和结束日期之间的所有值:

CREATE TABLE my_data (
  start_date DATE,
  end_date DATE
 );
 INSERT INTO my_data (start_date, end_date) VALUES
 ('2018-08-01 00:00:00+00', '2018-08-05 00:00:00+00'),
 ('2018-08-03 00:00:00+00', '2018-08-05 00:00:00+00'),
 ('2018-08-09 00:00:00+00', '2018-08-10 00:00:00+00');

SELECT DISTINCT all_dates.dates
FROM (
  SELECT dates.d AS dates
  FROM generate_series(
    (SELECT MIN(start_date) FROM my_data),
    (SELECT MAX(end_date) FROM my_data),
    '1 day'::interval
  ) AS dates(d)
) AS all_dates
INNER JOIN my_data
    ON all_dates.dates BETWEEN my_data.start_date AND my_data.end_date
ORDER BY all_dates.dates;

Here's the fiddle