I need to find a way to add a Session column in a SELECT query. I’m using SQL Server 2005.
Here’s the initial example data:
ID Name VisitCounter
1 TOM 1
2 TOM 2
3 TOM 3
4 DICK 1
5 DICK 2
6 DICK 3
7 DICK 4
8 HARRY 1
9 HARRY 2
10 TOM 1
11 TOM 2
12 DICK 1
13 DICK 2
I need to write a query that will add a column called ‘Session’ and then increment everytime the name changes and the visitcounter = 1.
So the query should result in this:
ID Name VisitCounter Session
1 TOM 1 1
2 TOM 2 1
3 TOM 3 1
4 DICK 1 2
5 DICK 2 2
6 DICK 3 2
7 DICK 4 2
8 HARRY 1 3
9 HARRY 2 3
10 TOM 1 4
11 TOM 2 4
12 DICK 1 5
13 DICK 2 5 and so on
Is this possible?
In your example data, the sessions do not overlap. If that is true in general, you could count the number of previously started sessions:
Working example at SQL Fiddle.