SQL Server Return Order Counts for multiple Date Ranges in Same Query -
the query below attempt @ returning # of orders branch, reference both 2 month , 12 month date span in same result set. works 12 month range, duplicates 2 month count across branches rather specific branch received orders. data below.
results of query below
ref,l12_cnt,l2_cnt,l12_branch,l2_branch,l12_orderdate,l2_orderdate cust1,1,2,branch1,branch3,2016-11-01,2016-12-15 cust1,2,2,branch2,branch3,2016-10-20,2016-12-15 cust1,3,2,branch3,branch3,2016-12-15,2016-12-15
what results should since branch3 branch 2 orders.
ref,l12_cnt,l2_cnt,l12_branch,l2_branch,l12_orderdate,l2_orderdate cust1,1,0,branch1,branch3,2016-11-01,2016-12-15 cust1,2,0,branch2,branch3,2016-10-20,2016-12-15 cust1,3,2,branch3,branch3,2016-12-15,2016-12-15
2 mos query results
ref,opendate,branch 12345,2016-12-13,branch3 12345,2016-12-15,branch3
12 month query results
ref,opendate,branch 12345,2016-11-01,branch1 12345,2016-10-12,branch2 12345,2016-09-30,branch2 12345,2016-11-03,branch3 12345,2016-11-18,branch3 12345,2016-11-18,branch3
sql query:
declare @today date set @today='2/7/2017' declare @12mos date declare @2mos date set @12mos=dateadd(yy,-1,@today) set @2mos=dateadd(mm,-2,@today) ;with last12mos (referral, rownum, rcount, opendate, branch) (select referral, row_number() on (partition referral,branch order opendate desc, branch desc, gfno desc) rownum, count(*) on (partition referral,branch) rcount, opendate, branch orders opendate between @12mos , @today ), last2mos (referral, rownum, rcount, opendate, branch) (select referral, row_number() on (partition referral,branch order opendate desc, branch desc, gfno desc) rownum, count(*) on (partition referral,branch) rcount, opendate, branch orders opendate between @2mos , @today ) select c.name, l12.rcount l12_count, l2.rcount l2_count, l12.branch l12_branch, l2.branch l2_branch, l12.opendate l12_orderdate, l2.opendate l2_orderdate agent c left join last12mos l12 on c.agentnum = l12.referral , l12.rownum = 1 left join last2mos l2 on c.agentnum = l2.referral , l2.rownum = 1 (l12.rcount >0)
Comments
Post a Comment