Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.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中给定唯一ID和条件日期的求和值_Sql_Sql Server - Fatal编程技术网

SQL中给定唯一ID和条件日期的求和值

SQL中给定唯一ID和条件日期的求和值,sql,sql-server,Sql,Sql Server,我想求和值,但只给定唯一ID和条件日期。我希望对行日期之前的ID的所有值求和。例如,我的表如下所示: ID|Date |Val| Val2 x |1/1/2016|1|0 y |1/1/2016|3|0 z |1/1/2016|2|0 x |2/1/2016|2|0 y |2/1/2016|0|0 z |2/1/2016|1|0 x |3/1/2016|0|0 y |3/1/2016|5|0 z |3/1/2016|2

我想求和值,但只给定唯一ID和条件日期。我希望对行日期之前的ID的所有值求和。例如,我的表如下所示:

ID|Date     |Val| Val2         
x |1/1/2016|1|0           
y |1/1/2016|3|0  
z |1/1/2016|2|0  
x |2/1/2016|2|0  
y |2/1/2016|0|0  
z |2/1/2016|1|0  
x |3/1/2016|0|0  
y |3/1/2016|5|0   
z |3/1/2016|2|0  
我希望它看起来像:

ID|Date     |Val| Val2         
x |1/1/2016|1|1           
y |1/1/2016|3|3  
z |1/1/2016|2|2  
x |2/1/2016|2|3  
y |2/1/2016|0|3  
z |2/1/2016|1|3  
x |3/1/2016|0|3  
y |3/1/2016|5|8   
z |3/1/2016|2|5  

有什么想法吗?跨列求和很简单,按分组对唯一ID上的行进行求和是合乎逻辑的,但是如何使用日期和ID跨行进行条件求和?

您正在查找累积求和:

select id, date, val,
       sum(val) over (partition by id order by date) as val2
from t;