简体   繁体   中英

finding date intervals start and end dates

I have a table like this (plus 10 more columns) containing more than 1 million of frequently updated records:

 id pid start_date          end_date  
  1 761 2011-07-25 00:00:00 2011-08-01 00:00:00
  2 761 2011-08-01 00:00:00 2011-08-22 00:00:00
  3 761 2011-08-22 00:00:00 2011-09-19 00:00:00
  4 802 2011-08-22 00:00:00 2011-09-19 00:00:00
  5 761 2011-06-05 00:00:00 2011-07-05 00:00:00

and would like to get result for a particular pid (761 in the example below) with all consecutive intervals combined:

 id pid start_date          end_date  
  1 761 2011-07-25 00:00:00 2011-09-19 00:00:00
  5 761 2011-06-05 00:00:00 2011-07-05 00:00:00

Currently I am doing this in the code, but would like to move this functionality entirely to the db side. Any ideas how to do this?

edit: start_date and end_date columns are of DATETIME type.

This is really much better done in code. Loop over the rows, when it's for the same product, update the end date, otherwise create a new array entry.

For an idea of how complex this is in SQL, see m y attempt at solving this in SQL Server :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM