这是表 users
的列。
+--------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+-----------------+------+-----+---------+----------------+
| uid | int(6) unsigned | YES | | NULL | |
| score | decimal(6,2) | YES | | NULL | |
| status | text | YES | | NULL | |
| date | datetime | YES | | NULL | |
| cid | int(7) unsigned | NO | PRI | NULL | auto_increment |
+--------+-----------------+------+-----+---------+----------------+
我想要用户的最新分数和最早分数之间的差异。我试过:
select co1.uid, co1.score, co1.date from users as co1, (select uid, score, min(date) from users group by uid) as co2 where co2.uid = co1.uid;
这是行不通的。我也试过了
select co1.uid, co1.score, co1.date from users as co1, (select uid, score, max(date) - min(date) from users group by uid) as co2 where co2.uid = co1.uid;
我得到的结果:http://pastebin.com/seR81WbE
我想要的结果:
uid max(score)-min(score)
1 40
2 -60
3 23
等等
最佳答案
我认为最简单的解决方案是两个join
:
select u.uid, umin.score, umax.score
from (select uid, min(date) as mind, max(date) as maxd
from users
group by uid
) u join
users umin
on u.uid = umin.uid and umin.date = u.mind join
users umax
on u.uid = umax.uid and umax.date = u.maxd;
我应该注意:如果你知道分数只会增加,你可以做更简单的事情:
select uid, min(score), max(score)
from users
group by uid;
关于mysql - 如何获取多行上的最新日期和最早日期之间的列差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34820606/