我有一个包含以下列的表格
id pl_date month scores kID
1 20015/02/04 02 9 244
2 20015/02/05 02 12 244
3 20015/02/08 02 8 244
4 20015/02/22 02 24 244
5 20015/03/10 03 10 244
6 20015/03/11 03 12 244
7 20015/03/12 03 10 244
8 20015/03/13 03 12 244
我的目标是使用 MySQL 的特定 SELECT 来计算分数差异
id pl_date month scores kID diff
1 2015/02/04 02 9 244 -3
2 2015/02/05 02 12 244 +4
3 2015/02/08 02 8 244 -16
4 2015/02/22 02 24 244 +14
5 2015/03/10 03 10 244 -2
6 2015/03/11 03 12 244 +2
7 2015/03/12 03 10 244 -2
8 2015/03/13 03 12 244 12
我尝试使用如下所示的子查询,但它不起作用。
SELECT b.id, (b.max_count-b.min_count) AS DIFF
FROM
(SELECT id, MAX(scores) as max_count, MIN(scores) as min_count
FROM myTable
WHERE month = 03 AND kID = 244
GROUP BY kID) b
最佳答案
您可以将表与其自身连接(自连接),但将 id 移动 1 来执行此操作:
select t1.*, ifnull(t1.scores - t2.scores, t1.scores) as diff
from table1 t1
left join table1 t2 on t1.id + 1 = t2.id
如果您只想在某些分组(如 kID)内计算差异,只需将这些条件添加到联接中即可。
另一种方法是使用相关子查询(这使用日期而不是 id 来确定后继者):
select
t1.*,
t1.scores
- ifnull(
(select scores
from table1
where pl_date > t1.pl_date
limit 1)
,0) as diff
from table1 t1
order by id;
Sample SQL Fiddle (两种方法)
关于mysql - 获取MySQL中值之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29077974/