在没有视图的select语句中运行总查询

时间:2014-03-18 02:45:21

标签: sql-server running-total

我必须按月查询一组正在运行的总数据。

e.g. 
Month                 Amount            Total
2014-01-01            100               100
2014-01-02            100               200
2014-01-03            100               300

该应用程序不允许创建视图或SP。它可以直接从表中选择数据。

e.g.
select Month,
       Amount, 
       Total -- This is my problem.
from   Table -- This is a table only.

欢迎任何想法,谢谢。

3 个答案:

答案 0 :(得分:2)

您可以使用OUTER APPLY

SELECT  T.Month,T.Amount,T2.Total
FROM    Table1  T
        OUTER APPLY
        (   SELECT  Total = SUM(Amount)
            FROM    Table1  T2
            WHERE   T2.Month  <= T.Month 
        ) T2;

correlated subquery

SELECT  T.Amount, 
        (   SELECT  Amount = SUM(Amount)
            FROM    Table1 T2
            WHERE   T2.Month <= T.Month 
        ) 
FROM    Table1 T

答案 1 :(得分:1)

最简单的方法是使用SQL Server 2012,因为它内置累积和:

select Month, Amount, 
       sum(Amount) over (order by Month) as Total -- This is my problem.
from Table; 

相关子查询方法遵循类似的结构:

select Month, Amount,
       (select sum(Amount) from table t2 where t2.Month <= t.Month) as Total
from Table t;

这些通常是我考虑的两种方法,因为它们都是标准的SQL。正如Vignesh所指出的那样,你也可以用cross apply来做(虽然在我写这篇文章时,他的查询不正确)。

答案 2 :(得分:0)

以下是创建运行总计的第二种方法:

SELECT t.month, t.amount, 
SUM(t.amount) OVER(PARTITION BY t.month ORDER BY t.month
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as [Total]
FROM [yourTable] AS t