比较上个月的totalamount与当前月份的结果

时间:2018-02-18 19:44:56

标签: sql sql-server

我想比较月,当前和上个月之间的总金额。问题出现在新的一年出现。

SELECT 
    currYear.orderyear, currYear.ordermonth, currYear.totalamount, 
    prevYear.totalamount
FROM 
    (SELECT 
         SUM(val) AS totalamount, 
         YEAR(orderdate) AS orderyear,
         MONTH(orderdate) AS ordermonth
     FROM 
         Sales.OrderValues 
     GROUP BY 
         YEAR(orderdate), MONTH(orderdate)
    ) AS currYear
LEFT JOIN 
    (SELECT 
         SUM(val) AS totalamount, 
         YEAR(orderdate) AS orderyear,
         MONTH(orderdate) AS ordermonth
     FROM 
         Sales.OrderValues 
     GROUP BY 
         YEAR(orderdate), MONTH(orderdate)
    ) AS prevYear ON currYear.orderyear = prevYear.orderyear
                  AND currYear.ordermonth = prevYear.ordermonth + 1
WHERE 
    currYear.orderyear = '2006' 
    OR currYear.orderyear = '2007'
ORDER BY 
    currYear.orderyear, currYear.ordermonth

table result

1 个答案:

答案 0 :(得分:2)

使用lag()。我不确定比较是什么,但这应该是大部分工作:

SELECT YEAR(orderdate) as orderyear, MONTH(orderdate) as ordermonth,
       SUM(val) as totalamount, 
       LAG(SUM(val)) OVER (ORDER BY YEAR(orderdate), MONTH(orderdate)) as prev_totalamount
FROM Sales.OrderValues 
GROUP BY YEAR(orderdate), MONTH(orderdate);

这确实假设您每个月都有数据,这种情况似乎很可能。