繁体   English   中英

复杂情况下的SQL自联接查询

[英]SQL Self-Join Query in a complicated case

我正在对数据进行汇总。 关于不同时期的不同价格。

在数据库上看起来像

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使用某些语句来完成此操作,但到目前为止,我还没有任何想法。

特别是不知道如何生成“行3”和“行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.

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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