【问题标题】:Return one record with the max value if there is multiple records如果有多条记录,则返回一条最大值的记录
【发布时间】:2022-01-11 03:54:57
【问题描述】:

我认为拥有一个显示三段数据的表格会很酷。表名称、上次更新的表、上次查询的表(任何形式)以及上次启动服务器的时间。

这是我想出来的,

SELECT OBJECT_NAME(OBJECT_ID) AS TableName,
last_user_update AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time' AS Last_Update,
(SELECT MAX(Last_Used_Date)
FROM (VALUES
(last_user_seek), 
(last_user_scan), 
(last_user_lookup)) 
AS value(Last_Used_Date)) 
AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time' AS Last_Used,
(SELECT [sqlserver_start_time] AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time'
FROM sys.dm_os_sys_info) AS Vaules_From 
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'DATABASENAME')
ORDER BY TableName ASC

我要解决的问题是,由于某些表有索引,我从某些表中获取了多条记录。

如果有多条记录,我只想返回一条具有最大值的记录。

【问题讨论】:

  • 看来你不应该在这里使用子查询,而是正常的聚合。但是,您可能需要取消透视 FROM 中的数据。
  • 旁白:如果您的查询有一些合理的缩进,我们会帮助您。

标签: sql sql-server tsql


【解决方案1】:

轻微的重构得到以下内容,由object_id聚合

select Object_Name(ix.object_id, ix.database_id) as TableName,
  Max(ix.last_user_update) at time zone 'UTC' at time zone 'Central Standard Time' as Last_Update,
  Max(v.lastused) at time zone 'UTC' at time zone 'Central Standard Time' as Last_Used,
  (select sqlserver_start_time at time zone 'UTC' at time zone 'Central Standard Time' from sys.dm_os_sys_info) as Values_From 
from sys.dm_db_index_usage_stats ix
cross apply (values(last_user_seek), (last_user_scan), (last_user_lookup))v(lastused)
where database_id = Db_Id('dbName')
group by database_id, object_id
order by TableName

【讨论】:

    猜你喜欢
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多