有没有办法在Excel中生成累积支点?

时间:2011-09-30 10:43:40

标签: tsql excel charts pivot

我有一些数据:

Week Commencing       Channel      Count
----------------------------------------
 01/05/2011             C1          02
 01/05/2011             C3          01
 08/05/2011             C2          03
 15/05/2011             C1          01

产生这个支点:

Week Commencing       C1       C2       C3
------------------------------------------
 01/05/2011           02                01
 08/05/2011                    03
 15/05/2011           01

但是,我希望这些值是累积的,而不是任何空白:

Week Commencing       C1       C2       C3
------------------------------------------
 01/05/2011           02       00       01
 08/05/2011           02       03       01
 15/05/2011           03       03       01

通过这种方式,我可以在此数据上创建堆积区域图,并显示通道的累积增长。

我可以看到一个可能的解决方案是“填充”源数据,以便所有渠道都有一周的行,并且还有一个额外的列数据,即每个渠道,周的计数累计 - 周...但是,这是一个额外的复杂性!

1 个答案:

答案 0 :(得分:0)

我能够通过几个CTE,一些笛卡尔联接以及主数据库中一个小数字表的帮助来实现这个目的:

WITH 
TestData AS (
    SELECT  CAST('01 May 2011' AS DATETIME) AS StartDate,'C1' AS Channel, 02 AS COUNT
    UNION
    SELECT  CAST('01 May 2011' AS DATETIME) AS StartDate,'C3' AS Channel, 01 AS COUNT
    UNION
    SELECT  CAST('08 May 2011' AS DATETIME) AS StartDate,'C2' AS Channel, 03 AS COUNT
    UNION
    SELECT  CAST('15 May 2011' AS DATETIME) AS StartDate,'C1' AS Channel, 01 AS COUNT
),

Data_CTE AS (
    SELECT Channel, DATEADD(d, -(DATEPART(dw, startdate)+5), CAST(startdate AS DATE)) WeekCommencing, SUM(Count) AS Count 
    FROM TestData
    GROUP BY DATEADD(d, -(DATEPART(dw, startdate)+5), CAST(startdate AS DATE)), Channel),

Sub_CTE AS (
    SELECT Dates.RefWeek, Channels.Channel, ISNULL((SELECT Count FROM Data_CTE WHERE Channel = Channels.Channel AND WeekCommencing = Dates.RefWeek) , 0) AS [Count]
    FROM
        (SELECT  DATEADD(day, number * 7, (SELECT MIN(WeekCommencing) FROM Data_CTE)) RefWeek
    FROM    ( SELECT DISTINCT
                    number
          FROM      master.dbo.spt_values
          WHERE     name IS NULL
        ) n
    WHERE   
        DATEADD(day, number * 7, (SELECT MIN(WeekCommencing) FROM Data_CTE)) <= (SELECT MAX(WeekCommencing) FROM Data_CTE)) AS Dates, 
        (SELECT DISTINCT Channel FROM Data_CTE) AS Channels)

SELECT 
    RefWeek, Channel, ( SELECT SUM(Count) FROM Sub_CTE WHERE Channel = s.Channel AND RefWeek <= s.RefWeek) 
FROM Sub_CTE s

ORDER BY s.Channel, s.RefWeek

问题是它不是真的非常容易理解,而且我肯定想知道当我以后回来看看时我的火焰是什么:) - 哦,好吧。