Mysql 复杂情况下的SQL自连接查询
我正在做一个数据总结。关于不同时期的不同价格 在数据库上看起来像Mysql 复杂情况下的SQL自连接查询,mysql,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
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自连接的语句来完成
但到目前为止,我还不知道该怎么做
尤其是不知道如何生成
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
这是一个好问题。几次编辑可以让它变得更好。1.用文字说明如何将表格转换为所需的输出,2。添加到目前为止您已经尝试过的。好的,我刚刚添加了一些关于这个问题的描述。