SUM()列基于其他列

时间:2016-01-25 09:53:44

标签: sql-server sql-server-2008 tsql

我有每周的销售计划数据表,其中包含几列:

SAL_DTDGID -- which is date of every Sunday, for example 20160110, 20160117
SAL_MQuantity --sum of sales plan value
SAL_MQuantityYTD --sum of plans since first day of the year 
SAL_CoreElement --sales plan data for few core elements
SAL_Site --unique identifier of place, where sale has happened

如何将SAL_MQuantityYTD中的值与SAL_MQuantity的值相加,因为自2016年的第一个记录到现在'对于每个站点和每个核心元素?

SAL_Site中提及的每个网站都有52行,每年对应一周的计数以及5个不同的SAL_CoreElement' s 例如:

SAL_DTDGID|SAL_MQuantity|SAL_MQuantityYTD|SAL_CoreElement|SAL_Site
20160110  |20000        |20000           |1              |1234
20160117  |10000        |30000           |1              |1234
20160124  |30000        |60000           |1              |1234

如果有什么事情不清楚,我会尝试解释。

3 个答案:

答案 0 :(得分:1)

不确定我是否完全理解您的问题,但这应该允许您重新创建SAL_MQuantityYTD的运行总和。将#test替换为您调用的表/视图。

SELECT *,
    (SELECT SUM(SAL_MQuantity)
     FROM #test T2
     WHERE T2.SAL_DTDGID <= T1.SAL_DTDGID
        AND T2.SAL_Site = T1.SAL_Site
        AND T2.SAL_coreElement = T1.SAL_coreElement) AS RunningTotal
FROM #test T1

如果你想创建年度数字,那么你也可以使用像这样的相关子查询

SELECT *,
    (SELECT SUM(SAL_MQuantity)
     FROM #test T2
     WHERE cast(left(T2.SAL_DTDGID,4) as integer) = cast(left(T1.SAL_DTDGID,4) as integer)
        AND T2.SAL_Site = T1.SAL_Site
        AND T2.SAL_coreElement = T1.SAL_coreElement) AS RunningTotal
FROM #test T1

编辑:刚看到,基本上是相同的答案,使用窗口功能。

答案 1 :(得分:0)

让我向你解释一个想法。请尝试以下。

Select A, B, 
(Select SUM(SAL_MQuantity)
   FORM [Your Table] 
   WHERE [your date column] between '20160101' AND '[Present date]') AS SAL_MQuantityYTD 
FROM [Your Table]

答案 2 :(得分:0)

我对您的问题的理解是,您希望每年获得SAL_MQuantity的年度总和(您可以简单地“如果您只想要2016年之后的地方”),SAL_Site,SAL_CoreElement。

下面的代码应该实现,并将在SQL 2008 r2上运行(即运行2005)。

&#39; ## T1&#39;是我用来测试的临时表名,用你的表名替换它。

Select distinct 
        sum (SAL_MQuantity) over (partition by 
                                    left (cast (cast (SAL_DTDGID as int) as varchar (8)),4)
                                    , SAL_Site 
                                    , SAL_CoreElement 
                                ) as Sum_SAL_DTDGID 
        ,left (cast (cast (SAL_DTDGID as int) as varchar (8)),4) as Time_Period
        , SAL_Site 
        , SAL_CoreElement
        from ##t1