T-SQL Group出问题 [英] T-SQL Group by problem
本文介绍了T-SQL Group出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于SQL的和函数我有问题
我有这样的原始数据:
Hi,
I have a problem regarding on sum function of SQL
I have a raw data like this :
Count Date Row
10 1/1/2013 1
10 1/2/2013 2
10 1/3/2013 3
现在我要总结一下:
Now i want this to sum up :
Sum Date
10 1/1/2013
20 1/2/2013
30 1/3/2013
这是我目前的疑问:
This is my current query :
declare @count int
declare @i int
set @i = 1
set @count = (select max(Row) from #test) -- equals to 3
while @i <= @count
begin
select sum(Count) as SumCount
, Date
from #test
where row between 1 and @i
group by Date
set @i = @i + 1
end
然而结果是这样的:
However the result was like this :
SumCount Date
10 1/1/2013
10 1/2/2013
10 1/3/2013
我发现这是我每个日期的分组问题,
请帮我解决这个问题!
I figured out that it was the grouping per Date that i was having the problem,
plese help me on this thanks!
推荐答案
你想要的是跑步总数。如果您使用此关键字搜索Google,则会找到多篇文章。
从这里开始更好:计算简单运行总计在SQL Server中 [ ^ ],在这里: http://www.sqlperformance .com / 2012/07 / t-sql-queries / running-totals [ ^ ]
请注意作者的表现和资源考虑因素。与您可能已经知道的命令式方法相比,它并不像看起来那么简单。
What you want is called "running total". If you search google with this keywords, you will find several articles.
Better start here: Calculating simple running totals in SQL Server[^], and here: http://www.sqlperformance.com/2012/07/t-sql-queries/running-totals[^]
Please note the performance and resource considerations made by the authors. It is not as straightforward as it looks compared with an imperative approach you might already know.
这篇关于T-SQL Group出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文