在 SQL 中计算运行值的最有效方法
可能的重复:
计算 SqlServer 中的运行总计
考虑此数据
Day | OrderCount
1 3
2 2
3 11
4 3
5 6
我如何获得此累积使用 T-SQL 查询的 OrderCount(running value) 结果集
Day | OrderCount | OrderCountRunningValue
1 3 3
2 2 5
3 11 16
4 3 19
5 6 25
我可以通过在实际查询中循环(使用 #table)或在我的 C# 代码隐藏中轻松地做到这一点,但它太慢了(考虑到我也得到了每个订单)天)当我处理数千条记录时,所以我正在寻找更好/更有效的方法,希望没有循环,比如递归 CTE 或其他东西。
任何想法将不胜感激。 TIA
Possible Duplicate:
Calculate a Running Total in SqlServer
Consider this data
Day | OrderCount
1 3
2 2
3 11
4 3
5 6
How can i get this accumulation of OrderCount(running value) resultset using T-SQL query
Day | OrderCount | OrderCountRunningValue
1 3 3
2 2 5
3 11 16
4 3 19
5 6 25
I Can easily do this with looping in the actual query (using #table) or in my C# codebehind but its so slow (Considering that i also get the orders per day) when im processing thousand of records so i'm looking for better / more efficient approach hopefully without loops something like recursing CTE or something else.
Any idea would be greatly appreciated. TIA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您似乎需要在客户端中使用这些结果而不是在另一个 SQL 查询中使用,因此您最好不要在 SQL 中执行此操作。
(我的评论中的链接问题显示了 SQL 中的“最佳”选项,如果确实有必要的话。)
建议将 Day 和 OrderCount 值作为一个结果集(
SELECT day, orderCount FROM yourTable ORDER BY day
),然后在 C# 中计算运行总计。您的 C# 代码将能够高效地迭代数据集,并且几乎肯定会优于 SQL 方法。这样做的目的是将一些负载从 SQL Server 转移到 Web 服务器,但总体上(并且显着)节省了资源。
As you seem to need these results in the client rather than for use within another SQL query, you are probably better off Not doing this in SQL.
(The linked question in my comment shows 'the best' option within SQL, if that is infact necessary.)
What may be recommended is to pull the Day and OrderCount values as one result set (
SELECT day, orderCount FROM yourTable ORDER BY day
) and then calculate the running total in your C#.Your C# code will be able to iterate through the dataset efficiently, and will almost certainly outperform the SQL approaches. What this does do, is to transfer some load from the SQL Server to the web-server, but at an overall (and significant) resource saving.
CTE(再次)来救援:
输出:
CTE's to the rescue (again):
The output: