sql server - SQL average not working as I expected -
below sql query... averages not averaging totals, rather displaying sum. not sure why though. can provide insight?
select avg(a.t1) '8:00-9:00', avg(a.t2) '9:00-10:00', avg(a.t3) '10:00-11:00', avg(a.t4) '11:00-12:00', avg(a.t5) '12:00-1:00', avg(a.t6) '1:00-2:00', avg(a.t7) '2:00-3:00', avg(a.t8) '3:00-4:00', avg(a.t9) '4:00-5:00', avg(a.t10) '5:00-6:00', avg(a.t11) '6:00-7:00', avg(a.t12) '7:00-8:00' (select count(case when cast(request_datetime time) between cast('07:00:00' time) , cast('08:00:00' time) 1 end) t1, count(case when cast(request_datetime time)between cast('08:00:00' time) , cast('09:00:00' time) 1 end) t2, count(case when cast(request_datetime time) between cast('10:00:00' time) , cast('11:00:00' time) 1 end) t3, count(case when cast(request_datetime time) between cast('11:00:00' time) , cast('12:00:00' time) 1 end) t4, count(case when cast(request_datetime time) between cast('12:00:00' time) , cast('13:00:00' time) 1 end) t5, count(case when cast(request_datetime time) between cast('13:00:00' time) , cast('14:00:00' time) 1 end) t6, count(case when cast(request_datetime time) between cast('14:00:00' time) , cast('15:00:00' time) 1 end) t7, count(case when cast(request_datetime time) between cast('15:00:00' time) , cast('16:00:00' time) 1 end) t8, count(case when cast(request_datetime time) between cast('16:00:00' time) , cast('17:00:00' time) 1 end) t9, count(case when cast(request_datetime time) between cast('17:00:00' time) , cast('18:00:00' time) 1 end) t10, count(case when cast(request_datetime time) between cast('18:00:00' time) , cast('19:00:00' time) 1 end) t11, count(case when cast(request_datetime time) between cast('19:00:00' time) , cast('20:00:00' time) 1 end) t12 , count(interaction_id) daycount rt_queue_delta datename( dw,request_datetime) in('monday','tuesday','wednesday','thursday','friday','saturday') , cast(request_datetime date) >= '05/01/2015' , department = 1)
you have implicit group doing counts in subquery , avg on single values (the counts), in query avgs no-ops.
throw away outer query , calculate avgs instead of counts in subquery:
count(case when val between... 1 end)
should become
avg(case when val between... val end)