gpt4 book ai didi

sql-server - 如何使用保留顺序的运行计数形成查询

转载 作者:行者123 更新时间:2023-12-03 17:42:46 25 4
gpt4 key购买 nike

我有一个如下所示的跟踪表

TraceTable

我想得到一个运行总计,它看起来像以下输出 - 我保留顺序非常重要 - 因为这是存储的 porcedures 的执行顺序 - 这将帮助我分析系统中的瓶颈

Output

我试过了

select max(RowNumber),objectname, count(1) from rob
where eventclass = 42
group by objectname

但这会破坏订单

这在 SQL 中是否可行?

更新:我试过这个

select RowNumber,objectname, count(1) from rob
where eventclass = 42
group by objectname,RowNumber
order by RowNumber

但是这个(因为查询非常正确地说按行号分组(必须有它才能按顺序排列))

最佳答案

select objectname, 
count(*)
from (
select RowNumber,
objectname,
row_number() over(order by RowNumber) - row_number() over(order by objectname, RowNumber) as grp
from rob
where eventclass = 42
) as T
group by grp, objectname
order by min(RowNumber)

使用表变量的工作示例。

declare @T table
(
RowNumber int,
objectname varchar(50)
)

insert into @T values
(8, 'f_system_log_init'),
(10, 'f_purge_system_log'),
(25, 'f_system_log_msg'),
(65, 'f_system_log_msg'),
(104, 'f_system_log_msg'),
(143, 'f_system_log_msg'),
(182, 'f_system_log_msg'),
(221, 'f_system_log_msg'),
(5015, 'f_get_system_logs_parent_log_id_for_dataloader'),
(5055, 'f_system_log_msg'),
(5096, 'f_system_log_msg')

select objectname,
count(*)
from (
select RowNumber,
objectname,
row_number() over(order by RowNumber) - row_number() over(order by objectname, RowNumber) as grp
from @T
) as T
group by grp, objectname
order by min(RowNumber)

结果:

objectname                                         
-------------------------------------------------- -----------
f_system_log_init 1
f_purge_system_log 1
f_system_log_msg 6
f_get_system_logs_parent_log_id_for_dataloader 1
f_system_log_msg 2

关于sql-server - 如何使用保留顺序的运行计数形成查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11841924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com