这是表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
等
答案 0 :(得分:0)
我认为最简单的解决方案是两个join
s:
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;