从上一个日期检索特定字段

时间:2012-06-12 19:10:35

标签: sql database date

以下信息目前存在于数据库中。

ID -- Company --- Current Value ---- Date
1 -- company1 ------- 12 --------- 25th March 2010
2 -- company1 ------- 17 --------- 25th March 2011
3 -- company2 ------- 65 --------- 23rd April 2011
4 -- company1 ------- 45 --------- 25th March 2012
5 -- company2 ------- 34 --------- 23rd April 2012

我是否有某种方法可以计算该字段以找出每家公司上一年的价值?

ID -- Company --- Current Value --- Last Year Value ---- Date
1 -- company1 ------- 12 ---------------- 0 --------- 25th March 2010
2 -- company1 ------- 17 --------------- 12 --------- 25th March 2011
3 -- company2 ------- 65 ---------------- 0 --------- 23rd April 2011
4 -- company1 ------- 45 --------------- 17 --------- 25th March 2012
5 -- company2 ------- 34 --------------- 65 --------- 23rd April 2012

我尝试了很多解决方案,包括搜索这个网站,但没有任何效果。

1 个答案:

答案 0 :(得分:0)

由于您的表格看起来的确具有相隔一年的日期,因此可以通过左侧加入来完成。

SELECT a.ID, 
    a.Company, 
    a.CurrentValue, 
    ISNULL(b.CurrentValue, 0) AS 'LastYearValue',
    a.Date
FROM dbo.Table a
LEFT JOIN dbo.Table b ON a.Company = b.Company AND b.Date = DATEADD(YEAR, -1, a.Date)