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

SQL累减语句

xjtudll3年前 (2022-02-07)技术心得4780

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

Windows Server 2008 R2上搭建ShadowSocks服务

Shadowsocks是一个轻量级隧道Socks5代理,可加密网络通道。 1、下载nodejs     首先要进入https://nodejs.org/,点击页面上的INSTALL安装相对应的node环境。 2、安装nodejs   &...

CTE递归限制次数

CTE递归限制次数

https://blog.csdn.net/weixin_30247159/article/details/98657005 CTE可以用来取递归,网上资料很多,这里就不再叙述了,今天遇到的需求是要限制只取2级,然后加了个临时的lev with tree as ( select [Cu...

插件中获取多级审核级次

oMultiMgr.CurrentLevel   Private Sub m_BillInterface_AfterLoadBill()     Dim oMultiMgr As Object     Set oMultiMgr...

金蝶K3 业务预警无法自动发送-自定义报表SQL语句发布到业务预警,无法自动发送出来

客户问题:业务预警无法自动发送:客户自己写的自定义报表SQL语句发布到业务预警,无法自动发送出来 解决方案:在客户的语句前加上:set nocount on 即可...

再谈无线网络受限——无法获得IP地址

前面曾经写了一篇[无线网络连接受限]的解决办法(http://www.xjtudll.cn/Exp/66/),本次再谈一些这方面的内容。上次无线网络受限导致的结果就是:无线网卡无法获得IP地址,即便信号很好,也一直连不上。上次最后的解决办法是用WEP加密方式,后来在网上看到WPA2-PSK加密方式更...

单片机IO输入输出配置

单片机IO输入输出配置

单片机IO简单的来说,分为输入和输出两种配置。而输入和输出里,又有一些更详细的配置。如下图所示: 输出配置,比较常见的有四种: (1) High-impedance output 高阻输出,可以简单的理解为悬空状态,它的输出随外界改变而改变。 (2) P-channel open drain...

发表评论

访客

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