How do I form a query with a running count retaini

2019-07-02 16:16发布

问题:

I have a trace table which looks like this

I'd like to get a running total which looks like the following output - its very important that I retain the order - as this is the execution order of the stored porcedures - It will help me analyze bottle necks in the system

I have tried

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

But that mucks up the order

Is this even possible in SQL?

UPDATE: I tried this

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

But this (as the query quite rightly says groups by rownumber (have to have that to have it in the order by) )

回答1:

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)

Working sample using a table variable.

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)

Result:

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


回答2:

Try this:

;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