Determining the session with the highest max count

最后都变了- 提交于 2019-12-25 01:52:23

问题


I have a table that has the following fields:

  • Visit_ID
  • CPCCID
  • Date
  • Time_IN
  • Time-Out
  • Course
  • LA_CPCCID

There are 3 sessions, 9-12, 12-3 and 3-6.

I need a script that will calculate which session has the most visitors.

I have this attached code that will determine the session # and the max count:

select Time_In ,
CASE
When cast(Time_In as time) >'12:00:00' and cast(Time_In as time) <='15:00:00' /* and 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 date = cast(GETDATE() as date)*/ then 'Session 3'

else 'Session 1'
end "sessions"
from Lab_Visits2;


select max(visit.cnt) 
from
(select course, count(course) cnt
from Lab_Visits2
group by Course) visit;

回答1:


If I'm understanding your question correctly, you want to return the session and course with the most visitors grouped by session/course. If so, this uses a couple of common-table-expressions to select the sessions, and then groups by session and course to get the count of visitors. Finally, using row_number to establish the max:

with cte as (
  select 
      case
        when cast(Time_In as time) >'12:00:00' and cast(Time_In as time) <='15:00:00' /* and 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 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
  • SQL Fiddle Demo

If I misunderstood and you only want the session with the highest count (regardless of course), then just remove the course field from all of the queries.



来源:https://stackoverflow.com/questions/28822877/determining-the-session-with-the-highest-max-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!