在sql中明智的两个月费用的差异

时间:2015-02-18 10:40:31

标签: sql-server

我试图找到sql中前一个月和当前月份的费用差异。

我有一张这样的表

Date       Amount Category
2/18/2015  100    Salary 
2/12/2015  150    Rent
2/21/2015  200    Allowances
1/4/2015   200    Salary
1/17/2015  50     Rent
1/20/2015  100    Allowances

现在我想要一个像这样的结果

Category    CurrentMonthAmount PreviousMonthAmount Difference

Salary      100                200                 100
Rent        150                50                  100
Allowances  200                100                 100

2 个答案:

答案 0 :(得分:0)

您是仅尝试在SQL中进行计算还是通过PHP等脚本进行计算?此外,您是否可以说明您是否为此操作选择了特定记录(我指的是特定行)。给出更多澄清

答案 1 :(得分:0)

尝试使用conditional Aggregate

;WITH cte
     AS (SELECT Category,
                Max(CASE WHEN Month([date]) = Month(Getdate()) and year([date]) =year(getdate()) THEN amount END) CurrentMonthAmount,
                Max(CASE WHEN Month([date]) = Month(Getdate()) - 1 and year([date]) =year(getdate()) THEN amount END) PreviousMonthAmount
         FROM   Yourtable
         GROUP  BY Category)
SELECT Category,
       CurrentMonthAmount,
       PreviousMonthAmount,
       [Difference]=Abs(CurrentMonthAmount - PreviousMonthAmount)
FROM   cte 

<强> SQLFIDDLE DEMO