sql server 2008 - SQL Query to calculate median and group by -
i have following table.
declare @tbl_result table ( id varchar(10), createdate datetime, people_code_id varchar(10), conversion_date datetime, campus varchar(20), days_took int ); this table has records january 01,2013 date of leads received , converted.
i needed find median time took convert leads arrived in last 10 weeks , group them campus able using sql query below
with cte_result ( select * @tbl_result createdate > dateadd(week, -10, getdate()) ) select campus , avg(days_took) mediantime ( select campus , days_took , row_number() on ( partition campus order days_took asc ) agerank , count(*) on ( partition campus ) campuscount cte_result ) x x.agerank in ( x.campuscount / 2 + 1, ( x.campuscount + 1 ) / 2 ) group x.campus i need plot trend on graph i.e. find records previous 10 weeks buckets , plot median on line chart - each line 1 campus. (grouped campus)
is cursor option? find leads of first 10 week starting jan 01, above sql query median, push temp table , find next 10 weeks , on.
or there better can do?
without trying optimise query, if need produce same result across multiple 10-week periods, can expand current (10 week ago today) ranges many ranges required, threading periodenddate throughout query shown below.
ms sql server 2012 schema setup:
query 1:
declare @tbl_result table ( id varchar(10), createdate datetime, people_code_id varchar(10), conversion_date datetime, campus varchar(20), days_took int ); -- fill table dummy data 2013-01-01 insert @tbl_result (createdate, campus, days_took) select dateadd(d, a.number, '20130101'), 'campus' + right(b.number, 10), abs(cast(newid() binary(6)) % 130) + 1 master..spt_values join master..spt_values b on b.type='p' , b.number < 50 -- 50 campuses a.type='p' , dateadd(d, a.number, '20130101') <= getdate(); -- first cte used create required number of 10-week periods n(number) ( select 0 union select number+1 n number <= datediff(week, '20130101', getdate()) ), -- , below here it's query periodenddate threaded through cte_result ( select dateadd(week, -number, getdate()) periodenddate, t.* @tbl_result t cross join n -- see range built dynamically here createdate > dateadd(week, -number-10, getdate()) , createdate < dateadd(week, -number, getdate()) +1 ) select periodenddate, campus , avg(days_took) mediantime ( select periodenddate, campus , days_took , row_number() on ( partition periodenddate, campus order days_took asc ) agerank , count(*) on ( partition periodenddate, campus ) campuscount cte_result ) x x.agerank in ( x.campuscount / 2 + 1, ( x.campuscount + 1 ) / 2 ) group x.periodenddate, x.campus order x.periodenddate, x.campus;
Comments
Post a Comment