sql运行总计

时间:2015-02-03 14:47:06

标签: sql sql-server

我试图按月和年生成一个总计。香港专业教育学院尝试了一些例子,但我不能让它工作。这是我的sql,我想为totalclients列创建一个运行总计

Month| Year| TotalClients| Running Total

Jan |2014| 1| 1

Feb| 2014| 4| 5

Mar| 2014| 8| 13


select Month, Year, TotalClients
From Total

这是我试图使用的代码,我使用了一个声明表,因为主要数据来自不同的查询,但这应该是你需要的。当我尝试两种方式时,我也注释了其中一条线,注释掉的线在网上的一些例子中但是我无法使它工作

select t1.monthstart, t1.yearstart, t1.TotalClients, sum(t2.TotalClients) as 'RunningTotal'
from @Totals t1 inner join  @Totals t2 on t1.monthstart = t2.monthstart and t1.yearstart = t2.yearstart
--from @Totals t1, @Totals t2 
WHERE t1.MonthStart <= t2.MonthStart and  t1.Yearstart <= t2.Yearstart
GROUP BY t1.Yearstart,  t1.MonthStart, t1.TotalClients
ORDER BY t1.yearstart , t1.monthstart

3 个答案:

答案 0 :(得分:1)

正如@xQbert在上面的评论中发表的那样(我建议阅读那篇文章),SQL Server“Windowing Functions”就是你想要在2012+版本中使用的。窗口函数灵活且功能强大,远比自连接更有效。

作为一个实际的答案,这里有一些可能的代码供您使用:

SELECT YearStart, MonthStart, 
    ClientCount = SUM(TotalClients) OVER (
        PARTITION BY YearStart, MonthStart 
        ORDER BY YearStart, MonthStart RANGE UNBOUNDED PRECEDING
    )
FROM Totals t1
ORDER BY YearStart, MonthStart

答案 1 :(得分:0)

此查询适用于SQL Server 2012及更高版本。我假设Month是数字(Jan = 1,Feb = 2等)

SELECT  *,
        SUM(t.TotalClients) OVER (PARTITION BY t.[Year] ORDER BY t.[Month])
FROM    @Totals t

一旦年度变化,它将重置客户端计数。为了保持这种状态,请将SUM子句更改为

SUM(t.TotalClients) OVER (ORDER BY t.[Year], t.[Month])

答案 2 :(得分:0)

我最后使用了这个,我添加了一个faulldate以简化我想要的并且它有效,我认为问题出在我使用它的连接中有&lt; =错误的方法。

SELECT
    st1.invoicestartdate,
    st1.TotalClients,
    RunningTotal = SUM(st2.TotalClients)
FROM
    @Totals AS st1
INNER JOIN
    @Totals AS st2
    ON st2.invoicestartdate <= st1.invoicestartdate
GROUP BY st1.invoicestartdate, st1.TotalClients
ORDER BY st1.invoicestartdate;