当前位置:首页 > 技术心得 > 正文内容

SQL累减语句

xjtudll4年前 (2022-02-07)技术心得7490

https://bbs.csdn.net/topics/70362619

表一
Item Qty
A 10
A 12
A 14
B 13
B 60
C 30
C 40
C 10
表二
Item Qty
A 1000
B 70
C 100
表三
Item Qty Result
A 10 990 =(1000-10)
A 12 978 =(990-12)
A 14 964 =(978-14)
B 13 57 =(70-13)
B 60 -3 =(57-60)
C 30 70 =(100-30)
C 40 30 =(70-40)
C 10 20 =(30-10)

--示例
--示例数据
create table 表一(Item varchar(10),Qty int)
insert 表一 select 'A',10
union all select 'A',12
union all select 'A',14
union all select 'B',13
union all select 'B',60
union all select 'C',30
union all select 'C',40
union all select 'C',10
create table 表二(Item varchar(10),Qty int)
insert 表二 select 'A',1000
union all select 'B',70
union all select 'C',100
go
--查询
select id=identity(int),a.*,Result=b.Qty
into # from 表一 a,表二 b
where a.Item=b.Item
order by a.Item
declare @Item varchar(10),@s int
update # set
@s=case when @Item=Item then @s-Qty else Result-Qty end,
@Item=Item,Result=@s
select * from #
drop table #
go
--删除测试
drop table 表一,表二
/*--结果
Item Qty Result
---------- ----------- -----------
A 10 990
A 12 978
A 14 964
B 13 57
B 60 -3
C 30 70
C 40 30
C 10 20
(所影响的行数为 8 行)
--*/

--示例
--示例数据
create table 表一(Item varchar(10),Qty int)
insert 表一 select 'A',10
union all select 'A',12
union all select 'A',14
union all select 'B',13
union all select 'B',60
union all select 'C',30
union all select 'C',40
union all select 'C',10
create table 表二(Item varchar(10),Qty int)
insert 表二 select 'A',1000
union all select 'B',70
union all select 'C',100
go
--查询
select id=identity(int),* into # from 表一
select a.Item,a.Qty,Result=b.Qty-(select sum(Qty) from # where Item=a.Item and id<=a.id)
from # a,表二 b
where a.Item=b.Item
drop table #
go
--删除测试
drop table 表一,表二
/*--结果
Item Qty Result
---------- ----------- -----------
A 10 990
A 12 978
A 14 964
B 13 57
B 60 -3
C 30 70
C 40 30
C 10 20
(所影响的行数为 8 行)
--*/

扫描二维码推送至手机访问。

版权声明:本文由鸟的天空发布,如需转载请注明出处。

本文链接:http://www.xjtudll.cn/Exp/632/

标签: SQL
分享给朋友:

“SQL累减语句” 的相关文章

金蝶 从旧账套拷贝供应链单据的自定义字段到全新帐套

金蝶 从旧账套拷贝供应链单据的自定义字段到全新帐套

补充几点:1、K3的官方的工具(K3单据自定义字段复制工具),要求在官方服务期,否则工具直接报错 2、涉及的表应该有以下几个:GLNoteCitationGLNoteTypeICChatBillTitleICClassTableInfoICClassTableInfoLayoutICTemplate...

程序加载水晶报表

重点就是doc.load ReportDocument doc = new ReportDocument();         TreeEntityList sources = new TreeEntityList (); &nb...

金蝶 报废/补料是否会参与倒冲领料

金蝶 报废/补料是否会参与倒冲领料

产品入库倒冲领料单没有考虑报废补料数量,一般领料时则会考虑。此种情况可以通专过【报废倒冲领属料】的功能生成【生产领料单】。 请按下列方法步骤操作: 1、登录K/3主控台,依次单击【生产管理】→【生产任务管理】→【生产物料报废/补料】,双击【生产物料报废/补料单-维护】; 2、打开...

PowerPCB转Protel

PowerPCB转Protel

第一步:用PowerPCB打开文件,选择Export导出,保存类型选择"ASCII Files(*.asc)",按保存按钮,弹出"ASCII Output"对话框,在导出格式(Format)中选择"PowerPCB V3.5",然后Sele...

“格林尼治时间”或将退休 明年全球将投票表决

          http://china.nfdaily.cn/content/2011-11/10/content_32922220.htm      &...

object-c 函数前面加号和减号 +和-的区别

简单来说就是: 加号 是可以通过类名直接调用这个方法; 减号则要实例化逸个对象,然后通过实例化的对象来调用该方法!! 使用的时候请注意。...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。