2016-07-26 47 views
1

我正在尋找一個MySQL查詢,讓我的產品的歷史價格變化稍後顯示在圖表上 - 基於日期範圍。接收日期範圍。如果開始約會不存在從最近的過去日期獲取範圍

例如:

Select * from HistoryPrices 
where StartDate>='1-1-2016' and EndDate<='1-20-2016' 
where ProductID=505 

這是好的。這是它變得更有趣的地方。 如果1-1-2016不包含任何商品價格變化,我需要取得過去最近的日期1-1-2016,並在結果中填寫1-1-2016

可以說12-25-2015是最接近的價格變化日期。

例子:

表如下所示:

Date  Price 
12-25-2015 44.5 
1-3-2016 50.5 
1-4-2016 45.6 
1-10-2016 40.99 
1-15-2016 50.50 
1-22-2016 50.99 

MySQL查詢結果應該(從2016年1月1日至二○一六年一月二十〇日):

1-1-2016 44.5 
1-3-2016 50.5 
1-4-2016 45.6 
1-10-2016 40.99 
1-15-2016 50.50 

公告價格1-1-2016得到12-15-2015價格。

尋找一個可以實現這個結果的MySQL查詢。

回答

1

試試這個爲您的樣品日期:

select * 
from HistoryPrices 
where `Date` >= date('2016-01-01') and `Date` <= date('2016-01-20') 
union (
    select '2016-01-01', Price 
    from HistoryPrices 
    where `Date` <= date('2016-01-01') 
    order by `date` desc 
    limit 1 
) 
order by `date` 

Demo Here

And Demo with 2016-01-01 included in data

+0

沒有與此查詢的問題。看樣本:http://sqlfiddle.com/#!9/dcf944/9它應該只返回一個結果(最後一個)而不是兩個結果。 – Dror

+0

@Dror所以如果最短日期不是'01',那麼你不需要這一天的'價格'? – Blank

+0

我的錯誤,在網址示例我給你它的作品..我不知道爲什麼,但在我的環境中,我得到另一個以前的價格與開始日期。不知道爲什麼。奇怪。查詢是一樣的。 – Dror