[英]SQL Select most recent record for each group
我正在尝试获取表中每个用户的最新记录:
SELECT *
FROM Orders
WHERE State = Active
GROUP BY UserId
ORDER BY Orders.DateTimePlanned DESC`
但这导致我在每个用户的最旧记录中,我怎样才能获得最新的记录? 将DESC
更改为ASC
不起作用!
请告诉我!
您的代码不是有效的标准 SQL。据推测,您正在运行 MySQL 并禁用 sql 模式ONLY_FULL_GROUP_BY
。
您需要过滤数据集而不是聚合它。 一个选项使用子查询:
select *
from orders o
where state = 'Active' and datetimeplanned = (
select max(o1.datetimeplanned)
from orders o1
where o1.userid = o.userid and o1.state = 'Active'
)
您还可以使用 window 函数(仅在 MySQL 8.0 中可用):
select *
from (
select o.*, rank() over(partition by userid order by datetimeplanned desc) rn
from orders o
where state = 'Active'
) o
where rn = 1
我会使用子查询
看看这个脚本,它使用子查询并获取最后一行并使用前一行的值减少它以预测数据库的数据增长
声明@backupType char(1), @DatabaseName sysname
set @DatabaseName = db_name() --> Name of current database, null for all databaseson server
set @backupType ='D' /* valid options are:
D = Database
I = Database Differential
L = Log
F = File or Filegroup
G = File Differential
P = Partial
Q = Partial Differential
*/
select backup_start_date
, backup_finish_date
, DurationSec
, database_name,backup_size
, PreviouseBackupSize
, backup_size-PreviouseBackupSize as growth
,KbSec= format(KbSec,'N2')
FROM (
select backup_start_date
, backup_finish_date
, datediff(second,backup_start_date,b.backup_finish_date) as DurationSec
, b.database_name
, b.backup_size/1024./1024. as backup_size
,case when datediff(second,backup_start_date,b.backup_finish_date) >0
then ( b.backup_size/1024.)/datediff(second,backup_start_date,b.backup_finish_date)
else 0 end as KbSec
-- , b.compressed_backup_size
, (
select top (1) p.backup_size/1024./1024.
from msdb.dbo.backupset p
where p.database_name = b.database_name
and p.database_backup_lsn< b.database_backup_lsn
and type=@backupType
order by p.database_backup_lsn desc
) as PreviouseBackupSize
from msdb.dbo.backupset as b
where @DatabaseName IS NULL OR database_name =@DatabaseName
and type=@backupType
)as A
order by backup_start_date desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.