SQL 为每个组选择最近的记录
Posted
技术标签:
【中文标题】SQL 为每个组选择最近的记录【英文标题】:SQL Select most recent record for each group 【发布时间】:2021-02-25 09:25:28 【问题描述】:我正在尝试获取表中每个用户的最新记录:
SELECT *
FROM Orders
WHERE State = Active
GROUP BY UserId
ORDER BY Orders.DateTimePlanned DESC`
但是这导致我每个用户的最旧记录,我怎样才能得到最新的!?将DESC
更改为ASC
不起作用!
请告诉我!
【问题讨论】:
标记您的 dbms 名称,如果支持窗口函数,请尝试使用 row_number() 或许可以在此处添加查询,以便社区可以使用它并向您显示更新后的查询 【参考方案1】:您的代码不是有效的标准 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'
)
您还可以使用窗口函数(仅在 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
【讨论】:
【参考方案2】:我会使用子查询
看看这个脚本,它使用一个子查询并取最后一行并使用前一行的值来减少它以预测数据库的数据增长
声明@backupType char(1) , @DatabaseName 系统名
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
【讨论】:
以上是关于SQL 为每个组选择最近的记录的主要内容,如果未能解决你的问题,请参考以下文章