2012-06-12 39 views
0

以下信息當前存在於數據庫中。檢索先前日期的特定字段

 
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 

我已經嘗試了許多解決方案,包括搜索本網站,但沒有任何工作。

回答

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) 
+0

我目前正在嘗試這個,但得到第4行與空語句錯誤 – user1452029

+0

什麼是錯誤? – stringpoet

+0

我改變它ifnull和它的工作。謝謝 – user1452029

相關問題