Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按列分组和按列聚合_Sql_Sql Server_Sql Server 2008_Group By_Aggregate Functions - Fatal编程技术网

Sql 按列分组和按列聚合

Sql 按列分组和按列聚合,sql,sql-server,sql-server-2008,group-by,aggregate-functions,Sql,Sql Server,Sql Server 2008,Group By,Aggregate Functions,我有一个要求,我的数据看起来像 Customer OpenBal Qty Date --------- ------- --- -------- 707001304 597 -48 20100414 707001304 597 -30 20100415 707001304 597 -30 20100419 707001304 597 -54 20100420 我想计算并获取数据 Customer OpenBal Qty

我有一个要求,我的数据看起来像

Customer   OpenBal  Qty  Date
---------  -------  ---  --------
707001304  597      -48  20100414
707001304  597      -30  20100415
707001304  597      -30  20100419
707001304  597      -54  20100420
我想计算并获取数据

Customer   OpenBal  Qty  Date      ClosingBal (OpenBal+Qty)
---------  -------  ---  --------  ----------
707001304  597      -48  20100414  549
707001304  549      -30  20100415  519
707001304  519      -30  20100419  489
707001304  489      -54  20100420  435
可以提供帮助,我如何按
Date
聚合
Qty
上的数据,并从
OpenBal
中减去当天的数据<一天的代码>结清余额将是第二天的期初余额


请告知。

也许我遗漏了什么,但是你不能用
+
添加列吗

select  Customer
,       OpenBal
,       Qty
,       Date
,       OpenBal + Qty as ClosingBal
from    YourTable
这可能有助于:

SELECT Customer, OpenBal, Date, SUM(OpenBal + Qty) AS Closingbal FROM Table_Name
GROUP BY Date, Customer, OpenBal

原始表的每一行都包含相同的OpenBal。OP希望它成为前一天的闭门

对于Oracle 10g、11g、SQL Server 2012和DB2 9.5,您可以使用LAG函数访问以前计算的值

insert into t_Customer values

(707001304,597,-48,20100414),
(707001304,597,-30,20100415),
(707001304,597,-30,20100419),
(707001304,597,-54,20100420)

select * from t_Customer

;WITH CTE as(select ROW_NUMBER() over (order by Customer) as sno,Customer,OpenBal,Qty,date,OpenBal+Qty as clsBal from t_Customer)
,CTE1 as (
select sno,Customer,OpenBal,Qty,date,clsBal from CTE where sno=1
union all
select c.sno,c.Customer,c1.clsBal,c.Qty,c.date,c1.clsBal+c.qty from CTE1 c1 inner join CTE c on c1.sno+1 =c.sno 
)
SELECT * FROM CTE1

你能给出这个表的结构吗。。表格显示可能有助于更好地理解问题。您使用的是哪个数据库?MySQL,SQL Server 2008,Oracle?嗨,Subir,它实际上来自多个表。尊敬的ShivHi Andomar,其Sql Server 2008。在这方面,原始表的每一行都包含相同的
OpenBal
。OP希望它是前一天的
CloseBal
@AndriyM:Aha,我知道问题没那么简单。现在,答案将取决于DBMS,我认为是的,它工作正常。非常感谢你及时的帮助和问候,希夫