0

我有这个 mysql 查询

SELECT YEAR(date_entered), MONTHNAME(date_entered), SUM(amount)
FROM opportunities
GROUP BY YEAR(date_entered), MONTH(date_entered);

这带回了这些数据

"year(date_entered)","monthname(date_entered)","sum(amount)"
"2009","March","9038714.77"
"2009","April","2205819"
"2009","May","9706852.6"

我需要做的是显示差异?例如,三月是 903,四月是 220,所以差值为 680,依此类推,所以最新的总和值减去宝贵的月份值?

提前致谢

4

2 回答 2

0

我会使用带有变量的查询,如下所示:

SELECT
  year_entered, month_entered,
  total_amount-@last_sum diff,
  @last_sum:=total_amount total_amount
FROM (
  SELECT
    YEAR(date_entered) year_entered,
    MONTHNAME(date_entered) month_entered,
    SUM(amount) total_amount
  FROM
    opportunities
  GROUP BY
    YEAR(date_entered), MONTH(date_entered)
  ORDER BY
    YEAR(date_entered), MONTH(date_entered)
  ) s,
  (SELECT @last_sum:=null) r

在此处查看小提琴。

于 2013-04-28T21:56:21.160 回答
0

尝试

SELECT year_entered, 
       month_entered,
       IFNULL(amount - @n, 0) amount_diff,
       @n := amount current_amount
  FROM
 (SELECT YEAR(date_entered) year_entered, 
         MONTHNAME(date_entered) month_entered, 
         SUM(amount) amount
    FROM opportunities
   GROUP BY YEAR(date_entered), MONTH(date_entered)) q, 
 (SELECT @n := NULL) n
于 2013-04-28T21:56:28.930 回答