如何使用保留订单的运行计数形成查询

时间:2012-08-07 08:24:46

标签: sql-server sql-server-2008 query-optimization

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

TraceTable

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

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

但是这个(因为查询非常正确地通过rownumber表示组(必须按顺序将它包含在内))

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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