|
saad.ahnad@gmail.com
Starting Member
15 Posts |
Posted - 2007-10-12 : 13:22:54
|
| Hello !!Environment: SQLServer 2005 SP2What is the best way to get YTD and QTD type of data in SQLServer 2005. I am using "cross apply" syntax - Is that the best (fastest) approach.Data.month, customer, sale1/1/2007, CST1, 101/1/2007, CST1, 202/1/2007, CST1, 303/1/2007, CST2, 404/1/2007, CST2, 305/1/2007, CST1, 10Outputmonth, customer, month_sale, YTD_sale1/1/2007, CST1, 30, 302/1/2007, CST1, 30, 603/1/2007, CST2, 40, 404/1/2007, CST2, 30, 705/1/2007, CST1, 10, 100select x.*, ca.ytdfrom(select month, customer, sum(sale)from sale_date d group by month, customer) x cross apply ( select ytd = sum(d1.sale) from sale_date d1 where year(d1.month) = year(x.month) ) caDDLS for Referencedrop table saad_tempselect *into saad_tempfrom (select cast('1/1/2006' as datetime) sale_date, 'CST1' cstnum, 50 saleunion allselect cast('2/1/2006' as datetime) sale_date, 'CST1' cstnum, 20 saleunion allselect cast('4/1/2006' as datetime) sale_date, 'CST2' cstnum, 20 saleunion allselect cast('1/1/2007' as datetime) sale_date, 'CST1' cstnum, 10 saleunion allselect cast('1/1/2007' as datetime) sale_date, 'CST1' cstnum, 20 saleunion allselect cast('2/1/2007' as datetime) sale_date, 'CST1' cstnum, 30 saleunion allselect cast('3/1/2007' as datetime) sale_date, 'CST2' cstnum, 40 saleunion allselect cast('4/1/2007' as datetime) sale_date, 'CST2' cstnum, 30 saleunion allselect cast('5/1/2007' as datetime) sale_date, 'CST1' cstnum, 10 sale) x --Saad Ahmadsaad.ahmad@gmail.com |
|