Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group repeated rows in TSQL

I have the following table and data in SQL Server 2005:

create table LogEntries (
  ID int identity,
  LogEntry varchar(100)
)

insert into LogEntries values ('beans')
insert into LogEntries values ('beans')
insert into LogEntries values ('beans')
insert into LogEntries values ('cabbage')
insert into LogEntries values ('cabbage')
insert into LogEntries values ('beans')
insert into LogEntries values ('beans')

I would like to group repeated LogEntries so that I have the following results:

LogEntry  EntryCount
beans     3
cabbage   2
beans     2

Can you think of any way to do this in TSQL outside of using a cursor?

like image 243
Lance Fisher Avatar asked Dec 12 '25 22:12

Lance Fisher


1 Answers

I think this will do it... didn't check too thoroughly though

select 
    COUNT(*),subq.LogEntry 
from 
(
    select 
        ROW_NUMBER() OVER(ORDER BY id)-ROW_NUMBER() OVER(PARTITION BY logentry ORDER BY id) as t,*
    from 
        LogEntries
) subq 
group by 
    subq.t,subq.LogEntry 
order by 
    MIN(subq.ID)
like image 193
spender Avatar answered Dec 15 '25 13:12

spender