将上个月的总金额与当前月份的结果进行比较

Posted

技术标签:

【中文标题】将上个月的总金额与当前月份的结果进行比较【英文标题】:Compare totalamount from previous month with current month result 【发布时间】:2018-02-18 19:44:55 【问题描述】:

我正在尝试比较当前月份和上个月之间的总金额。当新的一年出现时,问题就来了。

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】:

使用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);

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

【讨论】:

以上是关于将上个月的总金额与当前月份的结果进行比较的主要内容,如果未能解决你的问题,请参考以下文章

(1/2)尊敬的神州行客户,您本期短信账单如下:计费周期09月01日至09月30日,您消费的总金额为510.27元...

mysql update,2个表,把第一个表中所有满足条件的字段值(金额),加总到另一个表的总金额里

如何用sql的日期函数,分别查出1月~12月每个月的销售金额?

将日期范围转换为月份范围,除以金额[不是啥程序]

ThinkPHP按月统计订单总金额

如何获取发送到以太坊地址的总金额