|
发表于 2020-6-11 14:30:01
|
显示全部楼层
create table T(产品名 char(1), 时间 datetime, 数量 int, 单价 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), 产品名, 时间=max(时间), 数量=sum(数量), 单价 into #T from T
where 时间 between '2016-12-01' and '2016-12-31'
group by 产品名, 单价
order by 时间
select *,单价2=isnull( (select 单价 from #T where ID=A.ID-1), 单价), 差价=单价-isnull( (select 单价 from #T where ID=A.ID-1), 单价) from #T A
--result
ID 产品名 时间 数量 单价 单价2 差价
----------- ---- ------------------------------------------------------ ----------- ------------ ------------ -------------
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) |
|