我的问题与this one on SO相同,但不同之处在于,如果随机递增的id
没有继续,我们应该怎么做。
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 |
+-------+------------+--------------+-------------+
答案 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
答案 2 :(得分:0)
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)