2013-02-18 65 views
1

我正在編寫一份報告,告訴我一月和十二月之間的購買金額是否有增加或減少。每個賬戶實例都有一個記錄,因此通常每個客戶有4個(如果是季度)到12個(如果是每月)記錄。我如何做一個SQL查詢來做這樣的事情?它基本上必須查看所有的月份,並說明在任何月份中是否有變化。用於比較每月購買金額增加或減少的SQL查詢

這是我目前有:

Yr/Mnth Amt  
1212 51.00 
1209 69.00 
1206 69.00  
1203 69.00 

這是我想看到的內容:

March June September December Amount Diff Increase or Decrease 
69.00 69.00 69.00  51.00  18.00   Decrease 

回答

0

你想是這樣的:

select case when amount1 > amount2 then 'increase' 
when amount2 < amount1 then 'decrease' 
else 'no change' 
end changetype 
from 
(select t1.something amount1, t2.somethingelse amount2 
from yourtable t1 join yourtable t2 on something 
etc) alias_required 

你應該能夠填補空白。

1

可能是您的報告中,您可以在SQLFiddle

使用

;WITH cte AS 
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY [Yr/Mnth]) AS Id 
    FROM dbo.purchase 
) 
    SELECT DATENAME(mm, DATEADD(mm, RIGHT(c1.[Yr/Mnth],2)-1, '20010101')) AS [Month], 
     c1.Amt, ISNULL(c2.Amt, c1.Amt) - c1.Amt AS 'Amount Diff', 
     CASE WHEN c2.Amt - c1.Amt > 0 THEN 'Decrease' 
       WHEN c2.Amt - c1.Amt < 0 THEN 'Increase'     
       ELSE '' END AS 'Increase or Decrease' 
    FROM cte c1 LEFT JOIN cte c2 ON c1.Id = c2.Id + 1 

演示