我需要一个mysql查询,即使记录与日期无关,也会按日期对每个ID进行最新记录。我不确定这是否可以使用mysql,但我感谢您提供任何帮助。
例如,假设我有下表:
user_id | total | timestamp
----------------------------
1 | -15 | jan 1
2 | -5 | jan 1
3 | -10 | jan 1
1 | -4 | jan 2
3 | -16 | jan 3
我希望它返回下表:
user_id | total | timestamp
----------------------------
1 | -15 | jan 1
2 | -5 | jan 1
3 | -10 | jan 1
1 | -4 | jan 2
2 | -5 | jan 2
3 | -10 | jan 2
1 | -4 | jan 3
2 | -5 | jan 3
3 | -16 | jan 3
如果您需要进一步说明,请与我们联系。 谢谢你的帮助。
答案 0 :(得分:0)
select user_id,
(select total
from t
where user_id=t2.user_id
and t.timestamp <= t2.timestamp
order by t.timestamp DESC LIMIT 1) as total,
timestamp
from
(
select user_id,timestamp
from
(select distinct user_id from t) t0
cross join
(select distinct timestamp from t) t1
) t2
order by timestamp,user_id