|
create table T(product name char(1), time datetime, quantity int, unit price decimal(10,1))
insert T select'A', '2016-11-01', 20, 15
union all select'A', '2016-11-08', 40, 15
union all select'A', '2016-11-28', 70, 14.5
union all select'A', '2016-12-01', 10, 14.5
union all select'A', '2016-12-15', 80, 14.8
union all select'A', '2016-12-25', 55, 14.8
select ID=identity(int, 1, 1), product name, time=max(time), quantity=sum(quantity), unit price into #T from T
where time between '2016-12-01' and '2016-12-31'
group by product name, unit price
order by time
select *, unit price 2=isnull( (select unit price from #T where ID=A.ID-1), unit price), difference=unit price-isnull( (select unit price from #T where ID=A.ID-1), unit price ) from #TA
--result
ID Product name Time Quantity Unit price Unit price 2 Difference
----------- ---- ----------------------------------- ------------------- ----------- ------------ -------- ---- -------------
1 A 2016-12-01 00:00:00.000 10 14.5 14.5 .0
2 A 2016-12-25 00:00:00.000 135 14.8 14.5 .3
(2 row(s) affected) |
|