获取最近6个月(不完整的月份)中的条目总数

时间:2018-12-12 10:30:51

标签: sql sql-server tsql sum

我的数据看起来像这样

ProductNumber | YearMonth | Number
1               201803      1
1               201804      3
1               201810      6
2               201807      -3
2               201809      5

现在,我要添加一个附加条目“ 6MSum”,它是每个ProductNumber最近6个月的总和(不是最近6个条目)。 请注意YearMonth数据不完整,每个ProductNumber之间都存在间隙,因此我不能仅使用最后6个条目作为总和。最终结果应如下所示。

ProductNumber | YearMonth | Number | 6MSum
1               201803      1        1
1               201804      3        4
1               201810      6        9
2               201807      -3       -3
2               201809      5        2

此外,我不想将总和插入表中,而是在诸如以下查询中使用它:

SELECT [ProductNumber],[YearMonth],[Number],
6MSum = CONVERT(INT,SUM...)
FROM ...

我发现很多解决方案都使用“期限内的总和”,但仅用于最后的X个条目,而不是用于“过去6个月内的YearMonth”的实际条件语句。

任何帮助将不胜感激!

它是一个SQL数据库

编辑/回答

似乎是这样,几个月之后的空白必须用数据填充,之后是类似的

sum(Number) OVER (PARTITION BY category 
                      ORDER BY year, week 
                          ROWS 6 PRECEDING) AS 6MSum

应该工作。

解决方案的参考:https://dba.stackexchange.com/questions/181773/sum-of-previous-n-number-of-columns-based-on-some-category

4 个答案:

答案 0 :(得分:2)

您可以走OUTER APPLY路线。以下内容将完全产生您所需的结果:

-- prep data 
SELECT 
    ProductNumber , YearMonth , Number  
into #t
FROM ( values 
    (1,  201803 ,     1  ),
    (1,  201804 ,     3  ),
    (1,  201810 ,     6  ),
    (2,  201807 ,     -3 ),
    (2,  201809 ,     5  )
) s (ProductNumber , YearMonth , Number)

-- output
SELECT 
    ProductNumber 
    ,YearMonth 
    ,Number 
    ,[6MSum]
FROM #t t
outer apply ( 
    SELECT 
        sum(number) as [6MSum]
    FROM #t it
    where 
        it.ProductNumber = t.ProductNumber 
    and it.yearmonth <= t.yearmonth 
    and t.yearmonth - it.yearmonth between 0 and 6    
) tt


drop table #t

答案 1 :(得分:2)

使用outer apply并将yearmonth转换为日期,如下所示:

with t as (
      select t.*,
             convert(date, convert(varchar(255), yearmonth) + '01')) as ymd
      from yourtable t
     )
select t.*, t2.sum_6m
from t outer apply
     (select sum(t2.number) as sum_6m
      from t t2
      where t2.productnumber = t.productnumber and
            t2.ymd <= t.ymd and
            t2.ymd > dateadd(month, -6, ymd)
     ) t2;

答案 2 :(得分:0)

因此,一个有效的查询(由我的同事提供)看起来像这样

SELECT [YearMonth]
 ,[Number]
 ,[ProductNumber]
 , (Select Sum(Number) from [...] DPDS_1 where DPDS.ProductNumber = 
DPDS_1.ProductNumber and DPDS_1.YearMonth <= DPDS.YearMonth and DPDS_1.YearMonth >= 
convert (int, left (convert (varchar, dateadd(mm, -6, DPDS.YearMonth + '01'), 112), 
6)))FROM [...] DPDS

答案 3 :(得分:0)

只需再提供一个选项。您可以使用getView() { if (!this.organizationViewCache$) { this.cache$ = this.baseApiDependenciesService.http.post( `my-api`, {}, this.getHeaders() ).pipe( shareReplay(1), catchError(this.handleError) ); setTimeout(() => { this.cache$ = null; }, 10000) } return this.organizationViewCache$; } 从YearMonth值构建有效日期,然后在日期范围内搜索值。

可在此处测试:https://rextester.com/APJJ99843

DATEFROMPARTS
相关问题