如何从mysql中的新值中减去列的旧值

时间:2014-09-20 07:39:23

标签: mysql

我的问题与this one on SO相同,但不同之处在于,如果随机递增的id没有继续,我们应该怎么做。

QUERY

create table sales_table (no int, date varchar(10), sales int);

insert into sales_table values (1, '1-Jan', 10000),
                               (3, '3-Jan', 12500),
                               (5, '4-Jan', 8000);

预期结果

+-------+------------+--------------+-------------+
| no    |    date    |     sales    |      diff   |        
+-------+------------+--------------+-------------+
| 1     |    1-Jan   |     10,000   |       0     |         
| 3     |    3-Jan   |     12,500   |       2500  |            
| 5     |    4-Jan   |     8,000    |      -4500  | 
+-------+------------+--------------+-------------+

3 个答案:

答案 0 :(得分:2)

为什么要使用子查询?

SELECT
    no,
    date,
    IF(@sales = 0, 0, sales - @sales) diff,
    @sales := sales AS sales
FROM
    sales_table, (SELECT @sales := 0) x 
ORDER BY no;

输出:

+------+-------+-------+-------+
| no   | date  | diff  | sales |
+------+-------+-------+-------+
|    1 | 1-Jan |     0 | 10000 |
|    3 | 3-Jan |  2500 | 12500 |
|    5 | 4-Jan | -4500 |  8000 |
+------+-------+-------+-------+

答案 1 :(得分:0)

您可以使用用户定义的变量来存储销售的上一行值

SELECT 
t1.no,
t1.date,
t1.sales,
t1.diff
FROM (
SELECT 
*,
CASE WHEN @rownum = 0 THEN 0 ELSE s.sales - @prev END AS diff,
@prev:=s.sales,
@rownum:= @rownum +1 rownum
FROM sales_table s
CROSS JOIN (SELECT @prev:=0,@rownum:=0) t
ORDER BY s.no
) t1

Demo

答案 2 :(得分:0)

<强> QUERY

SELECT
curr.no,
curr.date,
curr.sales,
COALESCE(IFNULL(curr.sales, 0) - next.sales,0) AS Diff
FROM sales_table  AS curr
LEFT JOIN sales_table AS next
ON next.no = 
(SELECT MAX(no) 
FROM sales_table 
WHERE no < curr.no)

FIND FIDDLE HERE