mysql - SQL Self-Join Query in a complicated case -


i working on data sum up. different prices different periods.

on database looks

itemid | time start | price | time end   01   | 2012-01-01 | $10   | null   01   | 2013-01-01 | $20   | 2013-06-01   01   | 2014-01-01 | $30   | null 

and tricky part task askw me output form like

itemid | time start | time end   | price  01    | 2012-01-01 | 2013-01-01 | $10  01    | 2013-01-01 | 2013-06-01 | $20  01    | 2013-06-01 | 2014-01-01 | $10  01    | 2014-01-01 | null       | $30  

i think should done statement using sql self join far don't have idea this.

especially have no idea how generate 'row 3' , 'row 4'

01 | 2013-06-01 | 2014-01-01 | $10

problem descriptions: each price related specific time slot. , there cases like:

case 1: if time slot has start time , end time, show it.(simple)   case 2 : if end time null, fill end time next start time.  case 3: (difficult one), row's start time comes the end time others row,it has match last time slot's end time.  , end time row should match start time of next time slot. 

not highly efficient, should work:

select * ( select items1.itemid,        items1.timestart,        coalesce(items1.timeend, (select min(items2.timestart)                                    items items2                                   items2.itemid = items1.itemid                                     , items2.timestart > items1.timestart)),        items1.price   items items1 union select items3.itemid,        items3.timeend,        (select min(items4.timestart)           items items4         items4.itemid = items4.itemid           , items4.timestart > items3.timeend),        (select items5.price           items items5          items5.timestart = (select max(items6.timestart)                                      items items6                                     items6.itemid=items5.itemid                                       , items6.timestart < items3.timestart)        )   items items3  items3.timeend not null ) itemss order 2 asc 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -