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

SQL累减语句

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

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累减语句” 的相关文章

TM87系列Mask Option

TM87系列Mask Option

1 Power Source 电源来源 A:...

Protel99SE交叉线节点处理

Protel99SE交叉线节点处理

在画电路图时,不可避免的会出现十字的交叉线,虽然Protel99SE默认不会在十字交叉处有节点(Junction),但是当你移动原理图的时候,Protel99SE会自动给加上个节点,这点就很不爽了,如图1和图2。    图1 移动前无节点 图2 移动后自动多了节点 但是...

金蝶K3提示:拒绝的权限

金蝶K3提示:拒绝的权限

http://blog.sina.com.cn/s/blog_c0ee51310102yyy0.html 在服务器上做了如下操作: 1、关闭掉中间层服务器的数据执行保护:cmd运行窗口输入 bcdedit.exe /set nx AlwaysOff ,重启生效。 2、在中间层服务器上打开控制面板&r...

WCF:在 ServiceModel 客户端配置部分中,找不到引用协定

环境:VS2010 + C#(DLL) + WCF 即我使用C#编写了一个DLL,在DLL里面远程调用WCF服务,然后EXE程序在调用DLL里面的接口时,出现了如下错误: System.InvalidOperationException: 在 ServiceModel 客户端配置部分中,找不到引用协...

DB9串口引脚定义

DB9串口引脚定义

DB9针式(DB9/F 公)  DB9孔式(DB9/M 母)DB9串口引脚定义如下:  针脚 功能 针脚 功能...

Multisim仿真过慢

Multisim仿真过慢

在用Multisim仿真的时候,有时候会仿真过慢,实际等了半天,而传递函数才走了几秒而已,有时候要看最后稳定的结果,得等N长时间,这个是无法忍受的。这个问题实际上是所有Spice类软件的通病,如果你按照软件的默认设置的话,有些仿真进程就是很慢。 解决办法: 修改仿真的步进值。如图(以中文版为例)...

发表评论

访客

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