Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 previous encounter data

Author  Topic 

Flamingo
Starting Member

1 Post

Posted - 2015-03-18 : 07:25:03
Hello
Please can someone help me?

I have a large table containing some information about Students.
sample:
Student ID / Date of Visit / Detail
1 / 01/04/2015 / A
2 / 01/04/2015 / A
3 / 07/01/2015 / B
4 / 07/04/2015 / B
5 / 13/04/2015 / B
1 / 14/04/2015 / B
2 / 15/04/2015 / B
4 / 15/04/2015 / B
5 / 15/04/2015 / A
1 / 15/04/2015 / B
1 / 17/04/2015 / C
1 / 01/05/2015 / C
2 / 01/05/2015 / C
6 / 01/05/2015 / D
8 / 12/05/2015 / D
9 / 17/05/2015 / B
10 / 18/05/2015 / A

What I would like to get is a list of students that have had multiple attendances (but i'm only interested in seeing them if their latest visit was within 30 days of the previous visit)

I would like to be able to show do with the information is see information about their latest and previous visit.

For example - I would like to see for Student 1
ID Latest Visit Latest Detail Previous Visit Previous Detail
1 01/05/15 C 17/04/15 C

where as Student 9 would not show at all

I'm not sure where to start - any help would be appreciated!

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2015-03-18 : 12:41:09
Try this (change red section to your table):
with cte
as (select *
from (select *
,row_number() over(partition by [student id] order by [date of visit] desc) as rn
,count(*) over(partition by [student id]) as c
from dbo.students
) as a
where c>1
and rn<3
)
select l.[student id] as id
,l.[date of visit] as [latest visit]
,l.detail as [latest detail]
,p.[date of visit] as [previous visit]
,p.detail as [previous detail]
from cte as l
inner join cte as p
on p.[student id]=l.[student id]
and p.rn=l.rn+1
Go to Top of Page
   

- Advertisement -