问题
In my table there are two fields start and stop which stores the start time and stop time respectively.
for example the Start time = 2014-01-01 23:43:00 and stop = 2014-01-03 03:33:00. This timestamp needs to brokendown to.
1=> 2014-01-01 23:43:00 - 2014-01-02 00:00:00, as date 2014-01-01
2=> 2014-01-02 00:00:01 - 2014-01-03 00:00:00, as date 2014-01-02
3=> 2014-01-03 00:00:01 - 2014-01-03 03:33:00, as date 2014-01-03
as three different rows.
Here the problem is the difference in stop and start time varies say 1 day to 10 days.
To make it more complicate, in the above example i split the period on basis of date, this i need to split on basis of time ie. say split at time 02:30:00, so the spiting should e as follows.
1=> 2014-01-01 23:43:00 - 2014-01-02 02:30:00, as date 2014-01-01
2=> 2014-01-02 02:30:01 - 2014-01-03 02:30:00, as date 2014-01-02
3=> 2014-01-03 02:30:01 - 2014-01-03 02:30:00, as date 2014-01-03
4=> 2014-01-03 02:30:01 - 2014-01-03 03:33:00, as date 2014-01-04
Once the above split has done, i need to count the rows grouped by date.
I'm using PostgreSQL
.
Can anyone throw some light on this !!
Thanks!
回答1:
I think your "split by time" desired output sample is wrong and should in instead be this
1=> 2014-01-01 23:43:00 - 2014-01-02 02:30:00, as date 2014-01-01
2=> 2014-01-02 02:30:01 - 2014-01-03 02:30:00, as date 2014-01-02
3=> 2014-01-03 02:30:01 - 2014-01-03 03:33:00, as date 2014-01-03
If that is the case then this do it
select day, count(*)
from (
select generate_series(
(start_time - interval '2 hours 30 minutes')::date,
stop_time,
interval '1 day'
)::date as day
from t
) s
group by day
order by day
回答2:
Create a collateral table - period
and insert all possible periods in the table for let's say from now() -10 years to now()+10 years
.
In case of days periods it should be all days of the 20 years.
After that you can select from the period
table and JOIN your table with period extracting code
回答3:
You probably will need an additional table containing every date to join it to your base table.
If you had a table like dates
containing values like:
date_col
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
...
Then you can do a query like
SELECT GREATEST(start_time, date_col), LEAST(end_time,date_col + interval 1 day) FROM base_table
JOIN dates ON date_col BETWEEN start_time AND end_time
SQL not tested but it shows tha idea.
来源:https://stackoverflow.com/questions/22398982/split-single-row-into-multiple-rows-in-sql