1

我正在编写一份报告,该报告应该告诉我在 1 月和 12 月之间购买金额是否有任何增加或减少。帐户的每个实例都有一条记录,因此每个客户通常会有 4 条(如果是季度)到 12 条(如果是月度)记录。我如何进行这样的 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  
4

2 回答 2

1

可能对于您的报告,您可以使用它

 ;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

SQLFiddle上的演示

于 2013-02-18T22:42:01.220 回答
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

你应该能够填空。

于 2013-02-18T22:20:04.630 回答