我有一个表,它是用户登录时的集合条目.
username, date, value -------------------------- brad, 1/2/2010, 1.1 fred, 1/3/2010, 1.0 bob, 8/4/2009, 1.5 brad, 2/2/2010, 1.2 fred, 12/2/2009, 1.3 etc..
如何创建一个可以为每个用户提供最新日期的查询?
更新:我忘了我需要一个与最新日期一致的值.
select t.username, t.date, t.value from MyTable t inner join ( select username, max(date) as MaxDate from MyTable group by username ) tm on t.username = tm.username and t.date = tm.MaxDate
使用窗口函数(适用于Oracle,Postgres 8.4,SQL Server 2005,DB2,Sybase,Firebird 3.0,MariaDB 10.3)
select * from ( select username, date, value, row_number() over(partition by username order by date desc) as rn from yourtable ) t where t.rn = 1
我看到大多数开发人员使用内联查询而不考虑它对大数据的影响.
简单地说,您可以通过以下方式实现
SELECT a.username, a.date, a.value FROM myTable a LEFT OUTER JOIN myTable b ON a.username = b.username AND a.date < b.date WHERE b.username IS NULL ORDER BY a.date desc;
要获取包含用户最大日期的整行:
select username, date, value from tablename where (username, date) in ( select username, max(date) as date from tablename group by username )
SELECT * FROM MyTable T1 WHERE date = ( SELECT max(date) FROM MyTable T2 WHERE T1.username=T2.username )