有一个运行总的成本sql调用datatable

时间:2016-03-08 23:28:36

标签: c# sql asp.net datatable

我正在使用sql调用创建数据表:

 SqlDataAdapter Adp = new SqlDataAdapter("select CONVERT(DATETIME, IncDate, 103) AS IncDate, SUM(IncCost) AS IncCost from Incomings GROUP BY CONVERT(DATETIME, IncDate, 103) ORDER BY CONVERT(DATETIME, IncDate, 103)", con);

目前输出

03/04/2016 - 13
05/04/2016 - 26
08/04/2016 - 5
13/04/2016 - 16
23/04/2016 - 23

我想知道如何更改我的SQL查询,以便将每个成本添加到前一个成本,即运行总计。这看起来像

03/04/2016 - 13
05/04/2016 - 39
08/04/2016 - 44
13/04/2016 - 60
23/04/2016 - 83

目前仍然没有可行的解决方案,也不确定如何去做。提前致谢!

2 个答案:

答案 0 :(得分:3)

您可以尝试此操作并根据需要进行调整。如果您在SSMS中执行此操作,则更容易看到发生的情况。

SELECT MyTable.IncDate AS IncDate, SUM(MyTable.IncCost) OVER (ORDER BY MyTable.IncDate) AS IncCost FROM
(
SELECT 
    CONVERT(DATETIME, IncDate, 103) AS IncDate, 
    SUM(IncCost) AS IncCost
FROM 
    Incomings
GROUP BY CONVERT(DATETIME, IncDate, 103)
) AS MyTable
ORDER BY MyTable.IncDate

说明:内部SELECT语句允许我们进行分组并获取所有设置,以便数据采用我们想要的格式。然后我们使用内部选择像表一样来进行SUM和OVER,这样我们就可以获得运行总数。

答案 1 :(得分:0)

如果您使用的是ssms-2012或更高版本,请尝试以下查询:

select CONVERT(DATETIME, IncDate, 103) AS IncDate, SUM(IncCost) over (order by IncDate) AS IncCost from Incomings GROUP BY CONVERT(DATETIME, IncDate, 103) ORDER BY CONVERT(DATETIME, IncDate, 103)