sql - Select with formula that includes previous value -
sql - Select with formula that includes previous value -
declare @sales table ( code varchar(10) not null, date1 date not null, sales numeric(10, 2) not null, profits numeric(10, 2) not null ); insert @sales(code, date1, sales, profits) values ('q', '20140708', 0.51,21), ('q', '20140712', 0.3,33), ('q', '20140710', 0.5,12), ('q', '20140711', 0.6,43), ('q', '20140712', 0.2,66), ('q', '20140713', 0.7,21), ('q', '20140714', 0.24,76), ('q', '20140714', 0.24,12), ('x', '20140709', 0.25,0), ('x', '20140710', 0.16,0), ('x', '20140711', 0.66,31), ('x', '20140712', 0.23,12), ('x', '20140712', 0.35,11), ('x', '20140714', 0.57,1), ('c', '20140712', 0.97,2), ('c', '20140714', 0.71,3); select code, convert(varchar, date1, 104) sph_date_formato, cast(sum(sales) on ( order date1) numeric (18, 2)) sph_close @sales date1 > dateadd(month, -21, getdate()) , code = 'q'
this select gives me accmulated sales ordered date 'g' code , fine. need additional column calculates: (1+ previous day sales)*(1+ today sales) -1 ordered date 'g' code
can help this, please?
you can using cte, alter select query this
;with sales ( select code, convert(varchar, date1, 104) sph_date_formato, cast(sum(sales) on (order date1) numeric (18,2)) sph_close,row_number() over(order date1 asc) rowid @sales date1 >dateadd(month, -21, getdate()) , code='q') select s1.code,s1.sph_date_formato,s1.sph_close ,s2.sph_close sales_last_day sales s1 left outer bring together sales s2 on s1.rowid -1 = s2.rowid
sql sql-server
Comments
Post a Comment