给定日期时间间隔的递归分组和计数/最大记录

时间:2015-04-07 18:36:21

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

我打开了另一个问题,但希望这个问题更清晰,并且针对我需要帮助的问题。

示例数据:(下面包括SQL小提琴链接)

groupid     custid      cust_type   cust_date           data_total_1    data_total_2
CA123       ABC12345    SLE         January, 01 2014    5               10
CA123       ABC12345    SLE         February, 01 2014   2               5
CA123       ABC12345    SLE         March, 01 2014      7               11
CA123       ABC12345    SLE         April, 01 2014      7               4
FL444       BBB22222    SLE         January, 01 2014    2               3
FL444       BBB22222    SLE         March, 01 2014      7               21
FL444       BBB22222    SLE         July, 01 2014       3               9
WA999       ZZZ99909    NSLE        April, 01 2014      2               10
WA999       ZZZ99909    NSLE        May, 01 2014        4               9

对于每个给定的groupid,custid,cust_type组合,我需要在给定的时间间隔(3个月)内获取评估记录。我需要计算记录数并获取每个记录的“范围”内存在的max data_total_x值。

我的预期输出与此类似:

groupid     custid      cust_type   cust_date           custid_count    max_data_total_1    max_data_total_2
CA123       ABC12345    SLE         January, 01 2014    4               7                   11
CA123       ABC12345    SLE         February, 01 2014   3               7                   11
CA123       ABC12345    SLE         March, 01 2014      2               7                   11
CA123       ABC12345    SLE         April, 01 2014      1               7                   4
FL444       BBB22222    SLE         January, 01 2014    2               7                   21
FL444       BBB22222    SLE         March, 01 2014      1               7                   21
FL444       BBB22222    SLE         July, 01 2014       1               3                   9
WA999       ZZZ99909    NSLE        April, 01 2014      2               4                   10
WA999       ZZZ99909    NSLE        May, 01 2014        1               4                   9

包含示例数据和我尝试的SQL小提琴: http://sqlfiddle.com/#!6/ba5a53/10/0

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为应该这样做:

select
  groupid,
  custid,
  cust_type,
  f.custid_count,
  f.max_data_total_1,
  f.max_data_total_2
from records r
outer apply (
  select 
    count(*) as custid_count,
    max(data_total_1) as max_data_total_1,
    max(data_total_2) as max_data_total_2
  from
    records r2
  where
    r.groupid = r2.groupid and
    r.custid = r2.custid and
    r.cust_type = r2.cust_type and
    r2.cust_date <= dateadd(month, 3, r.cust_date) and
    r2.cust_date >= r.cust_date
) f

SQL小提琴:http://sqlfiddle.com/#!6/ba5a53/14