我有以下查询计算总数。我想计算运行总数而不是总计。我该如何修改查询?
请不要将其标记为重复,因为我必须修改此查询中的内容以获得所需的结果。查询构建是通过Windows应用程序用户选择动态完成的。
IF OBJECT_ID('tempdb..#mytemptable') IS NOT NULL
DROP TABLE #mytemptable;
SELECT
SUM(CAST([PT_100SCALED_VAL0] AS bigint)) AS PT_100SCALED_VAL0_TOTAL INTO #MYTEMPTABLE
FROM (
SELECT
t1.[timestamp],
t1.[PT_100SCALED_VAL0]
FROM [REPORT] t1
WHERE CONVERT(DATE, t1.[timestamp]) = @timestamp
) TEMPTABLE
SELECT
t1.[timestamp],
t1.[PT_100SCALED_VAL0],
RM_temp.*
FROM [REPORT] t1,
#MYTEMPTABLE RM_temp
WHERE
CONVERT(DATE, t1.[timestamp]) = @timestamp
我目前的结果如下:
[timestamp] [PT_100SCALED_VAL0] PT_100SCALED_VAL0_TOTAL
31/May/2016 12:01:37 PM 1 87173
31/May/2016 12:02:07 PM 2 87173
31/May/2016 12:02:37 PM 3 87173
31/May/2016 12:03:07 PM 4 87173
我希望它是:
[timestamp] [PT_100SCALED_VAL0] PT_100SCALED_VAL0_TOTAL
31/May/2016 12:01:37 PM 1 1
31/May/2016 12:02:07 PM 2 3
31/May/2016 12:02:37 PM 3 6
31/May/2016 12:03:07 PM 4 10
答案 0 :(得分:2)
试试这个
SELECT *,(SELECT SUM(pp.PT_100SCALED_VAL0)
FROM YourTable pp
WHERE pp.PT_100SCALED_VAL0 <= p.PT_100SCALED_VAL0
) AS RunningTotal
FROM YourTable p
我已使用以下
更新了您的INSERT INTO
SELECT
(SELECT SUM(CAST(t2.[PT_100SCALED_VAL0] AS bigint))
FROM [REPORT] t2
WHERE t2.PT_100SCALED_VAL0 <= TEMPTABLE.[PT_100SCALED_VAL0] AND CONVERT(DATE, TEMPTABLE.[timestamp]) = @timestamp
) AS PT_100SCALED_VAL0_TOTAL INTO #MYTEMPTABLE
FROM (
SELECT
t1.[timestamp],
t1.[PT_100SCALED_VAL0]
FROM [REPORT] t1
WHERE CONVERT(DATE, t1.[timestamp]) = @timestamp
) TEMPTABLE