3

我有一个看起来像这样的跟踪表

跟踪表

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

输出

我试过了

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

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

4

2 回答 2

7
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
于 2012-08-07T09:08:37.227 回答
2

试试这个:

;WITH CTE as (select *,ROW_NUMBER() over(order by rownumber,objectname) rn from test101)

,CTE1 as(
select *,1 as incr from CTE where rn=1 
union all
select t.*,
CASE WHEN t.objectname=c.objectname then incr else incr+1 end  as incr
from CTE t inner join CTE1 c
on t.rn=c.rn+1
)

select max(objectname),count(incr) from CTE1
group by incr
于 2012-08-07T09:23:23.970 回答