确定具有最高最大计数的会话

时间:2015-03-03 02:04:57

标签: sql count max

我有一个包含以下字段的表:

  • Visit_ID
  • CPCCID
  • 日期
  • Time_IN
  • 超时
  • LA_CPCCID

有3个会话,9-12,12-3和3-6。

我需要一个脚本来计算哪个会话访问者最多。

我有这个附加代码,用于确定会话#和最大计数:

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 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您希望以会话/课程分组的最多访问者返回会话和课程。如果是,则使用几个common-table-expressions来选择会话,然后按会话和课程分组以获取访问者的数量。最后,使用row_number建立最大值:

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

如果我误解了你只想要具有最高计数的会话(无论当然如何),那么只需从所有查询中删除课程字段。