我有一张表foo
,如下所示:
+----------+--------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+-------------------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| ts | timestamp | NO | | CURRENT_TIMESTAMP | |
| user | varchar(255) | YES | MUL | NULL | |
| a | varchar(255) | YES | MUL | NULL | |
| b | varchar(255) | YES | MUL | NULL | |
| c | float | YES | | NULL | |
+----------+--------------+------+-----+-------------------+----------------+
对于每组不同(用户,a,b),我想选择最新的时间戳和值c
我尝试过以下几种不同的运气
select distinct user, b, c, ts as ts_b
from (select max(ts) as ts_a from foo as max_ts)
where ts_a = ts_b;
我很感激你能给予的任何帮助。非常感谢你!
答案 0 :(得分:1)
怎么样
select user,b,c, max(ts) as ts_b from foo
group by user,b,c
<强>更新强>
您可以使用此子查询来获取所需内容。 f2将是与不同的user
,a
,b
匹配且具有最新ts
的foo行。这相当于MSSQL中的CROSS APPLY语句。
select f2.user,f2.a, f2.b,f2.c, f2.ts
from
(select distinct user,a, b from foo) f1
inner join foo f2
on f2.id =
(select id
from foo f3
where f3.user=f1.user and f3.a = f1.a and f3.b=f1.b
order by f3.ts desc
limit 1
)
答案 1 :(得分:0)
我会使用子查询。这是一种方法:
select f.*
from foo f
where (user, b, c, ts) in (select user, b, c, max(ts) from foo group by user, b, c);
这将为您提供整行。如果您只想要最大时间戳,那就是用作子查询的简单聚合。
答案 2 :(得分:0)
我喜欢Bob Vale关于做max和小组的答案,但你提到你可能想要其他价值。
如果您想要与该行关联的其他值,您可以使用像row_number()这样的窗口函数来获取您要查找的行,而不是它在组中。
select id, ts, user, a, b, c, row_rank
from (
select id, ts, user, a, b, c,
row_number() over (partition by user, b, c order by ts desc) as row_rank
from foo
) table_with_row_number
where table_with_row_number.row_rank = 1