如何在SQL Server的“我的条件”中使用聚合函数?
我有一个名为如何在SQL Server的“我的条件”中使用聚合函数?,sql,sql-server,stored-procedures,aggregate-functions,Sql,Sql Server,Stored Procedures,Aggregate Functions,我有一个名为VoucherEntry 这些是我的记录 ID VoucherOnlineID TransactionNumber Store Amount ------------------------------------------------------------- 120 137 26 1001 100 126 137 22
VoucherEntry
这些是我的记录
ID VoucherOnlineID TransactionNumber Store Amount
-------------------------------------------------------------
120 137 26 1001 100
126 137 22 2000 -56
128 137 30 3000 -20
133 137 11 2000 -5
现在我想添加两列,其中包含结转金额和余额金额。如果VoucherEntry.Amount=100
则进位列应为0,否则应显示如下
预期输出
ID VoucherOnlineID TransactionNumber Store Carry Amount Balance
---------------------------------------------------------------------------------
120 137 26 1001 0 100 100
126 137 22 2000 100 -56 44
128 137 30 3000 44 -20 24
133 137 11 2000 24 -5 19
更新
我们可以按ID
列或Date
列对记录进行排序,排序后记录将按上述顺序显示
您需要累积和的两种变化:
您需要累积和的两种变化:
sql Server 2008及以下版本
declare @t table(ID int,VoucherOnlineID int,TransactionNumber int,Store int,Amount int)
insert into @t VALUES
(120,137,26,1001,100)
,(126,137,22,2000,-56)
,(128,137,30,3000,-20)
,(133,137,11,2000,-5 )
select *
,isnull((Select sum(Amount) from @t t1
where t1.VoucherOnlineID=t.VoucherOnlineID
and t1.id<t.id ) ,0)Carry
,isnull((Select sum(Amount) from @t t1
where t1.VoucherOnlineID=t.VoucherOnlineID
and t1.id<=t.id ) ,0)Balance
from @t t
declare@t表(ID int,VoucherOnlineID int,TransactionNumber int,Store int,Amount int)
插入到@t值中
(120,137,26,1001,100)
,(126,137,22,2000,-56)
,(128,137,30,3000,-20)
,(133,137,11,2000,-5 )
挑选*
,isnull((从@t t1中选择总和(金额)
其中t1.VoucherOnlineID=t.VoucherOnlineID
和t1.idSQLServer2008及以下版本
declare @t table(ID int,VoucherOnlineID int,TransactionNumber int,Store int,Amount int)
insert into @t VALUES
(120,137,26,1001,100)
,(126,137,22,2000,-56)
,(128,137,30,3000,-20)
,(133,137,11,2000,-5 )
select *
,isnull((Select sum(Amount) from @t t1
where t1.VoucherOnlineID=t.VoucherOnlineID
and t1.id<t.id ) ,0)Carry
,isnull((Select sum(Amount) from @t t1
where t1.VoucherOnlineID=t.VoucherOnlineID
and t1.id<=t.id ) ,0)Balance
from @t t
declare@t表(ID int,VoucherOnlineID int,TransactionNumber int,Store int,Amount int)
插入到@t值中
(120,137,26,1001,100)
,(126,137,22,2000,-56)
,(128,137,30,3000,-20)
,(133,137,11,2000,-5 )
挑选*
,isnull((从@t t1中选择总和(金额)
其中t1.VoucherOnlineID=t.VoucherOnlineID
和t1.idplease标记您的dbms并清楚地解释您的逻辑。您如何对行进行排序?@Lamak按ID或Date
,您可以按ID或Date
对表进行排序,我现在将更新Lag(Amount)over(按VoucherOnlineID分区按日期排序)
在这里似乎是一个有用的功能,如果支持的话。对于数量不超过100的条目,如何计算进位?请标记您的dbms并清楚地解释您的逻辑。您如何对行进行排序?@Lamak byID或Date
,您可以按ID或Date
对表进行排序,我现在将更新Lag(amount)(按VoucherOnline订单按日期划分)
如果支持的话,在这里似乎是一个很有用的函数。对于金额不为100的条目,如何计算进位?请稍候,我来告诉您check@dneoth天才先生,我接受你的回答。我不想复制和粘贴。你能给我更多关于你的分区的信息吗?。Thanks@mohamedfaiz:partitionby
类似于G分组依据
无论凭证id在哪里更改,它都会重置计算。请稍候,我来check@dneoth天才先生,我接受你的回答。我不想复制和粘贴。你能给我更多关于你的分区的信息吗?。Thanks@mohamedfaiz:分区依据
类似于分组依据
它在凭证id更改。