2017-05-08 105 views
0

我有一個包含4個字段(日期,資產名稱,價格)的表格,在此表中,每個工作日每個資產有一個記錄。使用這個表,我想建立一個查詢,這將使我下面如何爲此場景構建SQL

(ASSETNAME,LastPrice,價格在一個月前,價格在一年前,價格3年前) 我將不勝感激任何幫助

+1

什麼是從寫試圖返回你想要的數據阻止你? – dfundako

+2

** **您的問題,並根據該數據添加一些示例數據和預期輸出。 [**格式化文本**](http://stackoverflow.com/help/formatting)請,[無屏幕截圖](http://meta.stackoverflow.com/questions/285551/why-may-i-not -upload圖像-的代碼上那麼當-要價-A-問題/ 285557#285557)。 –

+1

您正在使用哪些DBMS? Postgres的?甲骨文? DB2?火鳥? –

回答

0

所以基本上你有興趣用不同的日期標準做自我加入你原來的表格。

我認爲以下方法可行,但您可能希望在以前的價格不存在的情況下使用ISNULL,以便相應地設置輸出格式。

SELECT A.AssetName 
, A.Price as CurrentPrice 
, B.Price as LastYearPrice 
, C.Price as LastMonthPrice 
FROM Table A 
LEFT JOIN Table B -- LastYearPrice 
ON A.AssetName = B.AssetName 
AND A.Date = DATEADD(y, -1, B.Date) 
LEFT JOIN Table C -- LastMonthPrice 
ON A.AssetName = C.AssetName 
AND A.Date = DATEADD(m, -1, C.Date) 
+0

謝謝。它確實有效,但速度非常慢,而且我在查詢時遇到了一些小問題。當我們使用A.Date = DATEADD(y,-1,B.Date)作爲加入標準時,有些情況下該特定日期沒有數據(例如,今天的日期前一個月是假期或週末) 。在這種情況下,我仍然需要獲取前一天或之後一天的數據(任何一個都可以工作,但如果前一天是星期日,我們需要返回兩天才能獲取星期五的數據) –

+0

將它放在where子句中而不是join 。我會很快更新 – Hituptony

0
select assetname,max(lastprice) lastprice,max(price_a_month_ago) price_a_month_ago,max(price_a_year_ago) price_a_year_ago,max(price_3_years_ago) price_3_years_ago from 
(
select assetname, 
case when months_between(current_date,price_date) < 1 then price else null end as lastprice, 
case when months_between(current_date,price_date) = 1 then price else null end as price_a_month_ago, 
case when months_between(current_date,price_date) = 12 then price else null end as price_a_year_ago, 
case when months_between(current_date,price_date) = 36 then price else null end as price_3_years_ago 
from ASSET_TABLE 
)a group by assetname