我有一个包含4个字段的表(日期,资产名称,价格),在此表中,每个工作日每个资产有一条记录。使用这个表我想构建一个查询,它将给我以下
(AssetName,LastPrice,一个月前的价格,一年前的价格,3年前的价格) 我希望得到任何帮助
答案 0 :(得分: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)
答案 1 :(得分: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