以日期升序排 数量总额减去14后的结果 这sql怎么写

本文提供了一个SQL示例,展示了如何通过SQL语句实现数据表中产品的数量按日期升序排列,并根据特定条件调整数量。具体操作包括创建表、插入数据、更新数量以及查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

产品  数量 日期  单据号
a      10   9.1  001
a      3    9.2  002
a      4    9.3  003
a      2    9.4  004
以日期升序排 数量总额减去14后的结果
产品  数量 日期  单据号
a      3    9.3  003
a      2    9.4  004
这个sql 怎么写?

方法一:create table tb(产品 varchar(2),  数量 int, 日期 varchar(4), 单据号 varchar(4))
insert into tb
select 'a',10,'9.1','001' union all
select 'a',3,'9.2','002' union all
select 'a',4,'9.3','003' union all
select 'a',2,'9.4','004'

select * from tb
declare @num int,@t int
set @num=14
set @t=0
update tb set 数量=case when 数量>=@num then 数量-@num else 0 end,@num=@num-@t,
@t=case when 数量>=@num then @num else 数量 end

select * from tb where 数量>0
drop table tb

方法二:(未测试)

select t.p,case when (select sum(qty) from @t where dt<t.dt)<=14 then (select sum(qty) from @t where dt<=t.dt)-14 else qty end as qty,t.dt,t.num
from @t t
where (select sum(qty) from @t where dt<=t.dt)>14 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值