问题
I have a query that I need to write. Lab assistants will enter the information for students coming to the lab for help. the field are:
Visit_ID, Student_ID, Visit_Date, Time_In, Time_Out, Course, Asst_ID.
There are 3 sessions for time_in entry
Session 1 9-12
Session 2 12-3
Session 3 3-6
The query needs to determine which session on the current day had the most visitors. This is what I have so far:
with cte as
(
select
case
when cast(Time_In as time) >'12:00:00' and cast(Time_In as time) <='15:00:00' and Visit_Date = cast(GETDATE() as date)then 'Session 2'
when cast(Time_In as time) >'3:00:00' and cast(Time_In as time)<= '6:00:00' and Visit_Date = cast(GETDATE() as date) then 'Session 3'
else 'Session 1'
end session
/*course*/
from Lab_Visits2
), ctecnt as (
select session,/* course,*/ count(*) cnt
from cte
group by session /*course*/
)
select session, /*course,*/ (cnt)
from (
select session, /*course,*/ cnt, row_number() over (order by cnt desc) rn
from ctecnt
) t
where rn = 1
来源:https://stackoverflow.com/questions/28843265/sql-using-entered-time-to-find-session-with-most-visitors