复杂案例中的SQL自联接查询

时间:2015-06-02 19:05:51

标签: mysql

我正在研究数据总结。关于不同时期的不同价格。

数据库上的

看起来像

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

棘手的部分是任务要求我输出像

这样的表格
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 

我认为应该使用SQL Self Join来完成一些语句 但到目前为止,我没有任何想法这样做。

尤其不知道如何生成的'row 3'和'row 4'

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

问题描述:每个价格与特定时段相关。还有一些案例如:

Case 1: if the time slot has start time and end time, just show it.(simple) 

Case 2 : if the end time is Null, it will fill the End time from the next start time.

Case 3: (difficult one), This row's start time comes from the The end time from the others row,it has to match the last time slot's End time.  and the end time for this row should match to the start time of next time slot.

1 个答案:

答案 0 :(得分:0)

效率不高,但它应该做的工作:

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