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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With