2016-12-03 94 views
1

在我的rails(帶有postgresql)項目中,我有事件模型start_dateend_date字段。事件日期範圍不能重疊。我想獲得所有與事件有關的日期。有效記錄:獲取多個範圍的所有日期

例如:

| event id | start_date | end_date | 
| :------: | :--------: | :--------: | 
| 51  | 2011-09-27 | 2011-09-29 | 
| 70  | 2014-07-23 | 2014-07-26 | 
| 71  | 2014-06-30 | 2014-07-01 | 
| 77  | 2016-03-10 | 2016-03-11 | 

輸出:

[ 
    2011-09-27, 
    2011-09-28, 
    2011-09-29, 
    2014-07-23, 
    2014-07-24, 
    2014-07-25, 
    2015-08-26, 
    2014-06-30, 
    2014-06-31, 
    2014-07-01, 
    2016-03-10, 
    2013-03-11 
] 

我嘗試做了很多,與此代碼得到的結果:

Event 
    .pluck(:start_date, :end_date) 
    .map(&:compact).reject(&:empty?) # I have events with null start_date and end_date 
    .map{ |start_date, end_date| 
    (start_date.to_date..end_date.to_date).map(&:to_s) 
    } 
    .flatten 

但我認爲這是醜陋的,有沒有一種優雅的方式來解決我的問題?也許與postgresql,但我是新的postgresql。

+0

您的代碼會更好看,如果你只是重組它繞在一個範圍和實例方法,因此您可以:Event.has_start_and_end.dates_in_range.flatten –

回答

0

型號event.rb

def get_dates 
    [created_at, updated_at] 
end 

,並得到所有日期由:

Event.all.map(&:get_dates).flatten 

更新

改變功能get_dates。

def get_dates 
    (Date.parse(start_date.to_s)..Date.parse(end_date.to_s)).to_a 
end 
+0

感謝的答案,但是這是不是我想要得到的。在這種情況下,我只能得到開始日期和結束日期**,而不是'start_date'和'end_date' **之間的日期。 –

+0

啊,對不起。只需更改函數get_dates,查看我的更新 –

0

我找到了另一種方式來解決我的SQL查詢問題

SQL Fiddle

的PostgreSQL 9.3架構設置

CREATE TABLE events (
    id integer NOT NULL, 
    start_date date, 
    end_date date 
)/ 

INSERT INTO events (id, start_date, end_date) VALUES (51, '2011-09-27', '2011-09-29')/ 
INSERT INTO events (id, start_date, end_date) VALUES (70, '2014-07-23', '2014-07-26')/ 
INSERT INTO events (id, start_date, end_date) VALUES (71, '2014-06-30', '2014-07-01')/ 
INSERT INTO events (id, start_date, end_date) VALUES (77, '2016-03-10', '2016-03-11')/ 

查詢1

WITH duration AS (
    SELECT start_date as begins 
    , end_date as ends 
    FROM events 
    ) 
SELECT generate_series(duration.begins, duration.ends, '1 day':: interval):: date 
FROM duration; 

Results

|    generate_series | 
|-----------------------------| 
| September, 27 2011 00:00:00 | 
| September, 28 2011 00:00:00 | 
| September, 29 2011 00:00:00 | 
|  July, 23 2014 00:00:00 | 
|  July, 24 2014 00:00:00 | 
|  July, 25 2014 00:00:00 | 
|  July, 26 2014 00:00:00 | 
|  June, 30 2014 00:00:00 | 
|  July, 01 2014 00:00:00 | 
|  March, 10 2016 00:00:00 | 
|  March, 11 2016 00:00:00 |