如何在sql server 2008中获得前几个月总和的月度总和

时间:2015-03-23 12:38:09

标签: sql-server

我编写了一个SQL查询来将Total Active Customer作为

SELECT 
    Cast((Datepart(year,[p].Transdate)) as varchar(50)) + '-' + 
    Cast((Datepart(Month,[p].Transdate)) as varchar(50)) AS [Month/Year] ,
    Count(Distinct([c].CustomerID)) as [Active Customers] 
FROM 
    CustomerPoints as [p] 
INNER JOIN
    Customers AS [c] ON [c].[CustomerID] = [p].[CustomerID] 
WHERE
    [p].Transdate BETWEEN '2013-01-20' AND '2015-03-05' 
    AND [c].DistributorID = '1' 
    AND [p].[TransType] = 'D' 
    AND [p].[Litres] > '0'
GROUP BY  
    Cast((Datepart(Year,[p].Transdate)) AS varchar(50)) + '-' + 
    Cast((Datepart(Month,[p].Transdate)) AS varchar(50)) 
ORDER BY 
    Cast((Datepart(Year,[p].Transdate)) AS varchar(50)) + '-' + 
    Cast((Datepart(Month,[p].Transdate)) AS varchar(50)) ASC

我得到的输出为

Month/year    ActiveCustomer
----------------------------------
2013-1             1
2014-3             1
2015-2             1

但我希望输出为上个月的活跃成员+当月活跃成员

Month/year    Active Customer
-------------------------------    
2013-1             1
2014-3             2
2015-2             3

2 个答案:

答案 0 :(得分:1)

使用SUM([your column]) OVER (ORDER BY [your set of columns])

更多信息:How can I use SUM() OVER()

答案 1 :(得分:0)

试试这个,它将表CustomerPoints连接到它自己以获得运行总和:

;WITH CTE AS
(
    SELECT 
        dateadd(month, datediff(month, 0, [p].Transdate), 0) monthstart,
        count(distinct [p].CustomerID) cnt
    FROM 
        CustomerPoints as [p] 
    INNER JOIN
        Customers AS [c] ON [c].[CustomerID] = [p].[CustomerID] 
    LEFT JOIN
        CustomerPoints as [p2] ON [p2].[Transdate] <= [p].[Transdate]
        and [p2].[Transdate] >= '2013-01-20'
    WHERE
        [p].Transdate BETWEEN '2013-01-20' AND '2015-03-05' 
    GROUP BY  
        dateadd(month, datediff(month, 0, [p].Transdate), 0)
)
SELECT convert(char(7), CTE.monthstart, 126) [Month/Year], 
sum(CTE2.cnt) ActiveCustomer 
FROM CTE
LEFT JOIN
CTE as [CTE2] ON [CTE2].monthstart <= [CTE].monthstart
GROUP BY CTE.monthstart