mysql - 如何获取多行上的最新日期和最早日期之间的列差异

标签 mysql sql

这是表 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/

相关文章:

SQL Server : How to get rows where the date is older than X years?

mysql - 使用多个索引优化 MySQL 查询

php - 使用 mysql_real_escape_string() 进行用户输入是否安全

MySQL 存储过程 echo "rows affected"而不是所需的结果?

SQL Server : How to de-duplicate on two columns/conditions?

php - 从一个数据库中的多个表中选择最新记录(MYSQL PHP)

php - 选择具有多个相同项的位置

mysql - 如何在移动到下一行之前选择然后插入到同一行

sql - 处理 NULL 和空字符串值时编写联合查询的最佳方法

mysql - 根据 CONDITION 决定对哪个表进行 LEFT JOIN