Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey!

I want to have a sql server query that groups similar events, but the 'grouping value' may occur multiple times, for example:

I have a database which stores where "a person" was seen. The database contains :

Hallway
Hallway
Kitchen
Kitchen
Kitchen
Livingroom
Kitchen
Livingroom
Livingroom
Hallway

I want te query to produce te following result :
2 Hallway
3 Kitchen
1 Livingroom
1 Kitchen
2 Livingroom
1 Hallway

Thus, group by the same location but only if they immidiately follow eachother up. Can anyone help me? Oh, and by the way... in the end I need a Linq query (on EF 6) that produces the result, so writing linq immidiately is no problem...
Posted
Comments
PIEBALDconsult 18-Mar-15 17:34pm    
How do you know they'll come up in that order?
Eduard Keilholz 18-Mar-15 17:36pm    
Because there's a datetime field of the event, I left it out because I thought it would be irrelevant for the result.
PIEBALDconsult 18-Mar-15 17:42pm    
'Tisn't.

Here is an example linq query: Row_Number() with Partition By clause simulation[^]
The idea on SQL query is the same ;)

Note: you need to set partition by date (day) when person seeen each other ;)
 
Share this answer
 
v2
SQL
declare @tb table(str1 varchar(50))
insert into @tb (str1) values
('Hallway'),
('Hallway'),
('Kitchen'),
('Kitchen'),
('Kitchen'),
('Livingroom'),
('Kitchen'),
('Livingroom'),
('Livingroom'),
('Hallway')
;with cte0(str1,rno)
as
(
select str1, rno=row_number() over(order by (SELECT 1)) from @tb
),
cte1 (str1,rno,pro) as
(
select str1,rno,pno=rno- row_number() over(partition by str1 order by cte0.rno,str1) from cte0
)

select count(*) as cnt, t.str1 from cte0 t inner join cte1 t1 on t.rno=t1.rno   group by t.str1,t1.pro order by min(t.rno)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900