2017-05-08 110 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