计算计算列SQL Server上的运行总计

时间:2017-01-11 23:25:06

标签: sql-server tsql

我正在尝试计算SQL Server中计算字段的运行总计。我有两列看起来像这样:

TimeElapsed | CurrentValue
     0      |     0.003
     1      |     0.002
     2      |     0.001

我正在寻找:

TimeElapsed | CurrentValue |   CummuSum
     0      |     0.003    |     0.003
     1      |     0.002    |     0.005
     2      |     0.001    |     0.006

要获得第一个表,我编写了以下查询:

select 
    floor(datediff(hh,date1,date2)) as TimeElapsed,
    cast(count(date2) as float)/(select count(col3) from table) as CurrentValue 
from 
    table
group by 
    floor(datediff(hh,date1,date2))
order by 
    floor(datediff(hh,date1,date2)) asc;

第一个语句计算两个单独列的时间差,并使用floor函数删除任何分钟或秒。所以,如果我有1小时30分钟的差异,我所关心的只是1小时。选择部分中的第二个语句计算该范围内的项目与项目总数的百分比。 Date2中的值可以是NULL

我认为是在编写子查询,但是当我尝试总结CurrentValue列时,我总是得到Cannot perform an aggregate function on an expression containing an aggregate or a subquery.错误。

有人可以指导您获取总计吗?

1 个答案:

答案 0 :(得分:1)

如果使用SQL Server 2012+,则SUM()使用SELECT TimeElapsed, CurrentValue, CummuSum = SUM(CurrentValue) OVER (ORDER BY TimeElapsed) FROM ( SELECT TimeElapsed = DATEDIFF(HOUR, Date1, Date2), CurrentValue = CAST(COUNT(Date2) AS FLOAT) / (SELECT COUNT(Col3) FROM myTable) FROM myTable GROUP BY DATEDIFF(HOUR, Date1, Date2) ) T ORDER BY TimeElapsed; 将允许您达到运行总计。

例如,

WITH CTE AS
(
    SELECT TimeElapsed = DATEDIFF(HOUR, Date1, Date2),
           CurrentValue = CAST(COUNT(Date2) AS FLOAT) / (SELECT COUNT(Col3) FROM myTable)
    FROM myTable
    GROUP BY DATEDIFF(HOUR, Date1, Date2)
) 
SELECT TimeElapsed,
       CurrentValue,
       CummuSum = (SELECT SUM(CurrentValue) FROM CTE WHERE TimeElapsed <= C.TimeElapsed)
FROM CTE C;

实现此目的的另一种方法(可在SQL Server 2008中使用),是在select语句中使用带有子查询的CTE。

例如,

data.table