我有一张这样的表:
// mytable
+----+------+-------+-------------+
| id | type | score | unix_time |
+----+------+-------+-------------+
| 1 | 1 | 5 | 1463508841 | -- this (current output)
| 2 | 1 | 10 | 1463508842 |
| 3 | 2 | 5 | 1463508843 | -- this (current output)
| 4 | 1 | 5 | 1463508844 |
| 5 | 2 | 15 | 1463508845 | -- this (expected output)
| 6 | 1 | 10 | 1463508846 | -- this (expected output)
+----+------+-------+-------------+
这是我的疑问:
SELECT SUM(score), unix_time
FROM mytable
WHERE 1
GROUP BY type
这是当前输出:
+-------+-------------+
| score | unix_time |
+-------+-------------+
| 30 | 1463508841 |
| 20 | 1463508843 |
+-------+-------------+
如您所见,输出包含第一行的unix_time
。但我正试图选择最好的一个。
所以这里是预期输出:
+-------+-------------+
| score | unix_time |
+-------+-------------+
| 30 | 1463508846 |
| 20 | 1463508845 |
+-------+-------------+
我该怎么做?
答案 0 :(得分:1)
获取每种类型的最长时间和总数,并在类型上获取join
。
select tm.maxtime,tot.total
from (select max(unixtime) maxtime, type
from mytable
group by type) tm
join (SELECT SUM(score) total, type
FROM mytable
GROUP BY type) tot
on tot.type = tm.type
或只是
select max(unixtime) maxtime, sum(score) total
from mytable
group by type
答案 1 :(得分:1)
我认为您需要汇总值(分数)和最大值(unix_time)
SELECT type, SUM(score), max(unix_time)
FROM mytable
GROUP BY type
我省略了1因为似乎没有意义..
答案 2 :(得分:1)
我想你只想要max()
:
SELECT SUM(score), MAX(unix_time)
FROM mytable
WHERE 1
GROUP BY type;
MySQL几乎是唯一接受您的查询版本的数据库。您应该收到错误,因为unix_time
不在GROUP BY
中,而不是聚合函数的参数。