首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在给定的日期时间间隔内回收组记录和计数/最大记录

在给定的日期时间间隔内回收组记录和计数/最大记录
EN

Stack Overflow用户
提问于 2015-04-07 18:36:20
回答 1查看 30关注 0票数 0

我还有另外一个问题要问,但希望这个问题更加明确,并针对我需要帮助的问题。

示例数据:(下面包括Sample链接)

代码语言:javascript
运行
复制
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

对于每一个给定的石斑鱼,垫子,cust_type组合,我需要在给定的时间间隔(3个月)内获取评估记录。我需要计算记录的数量,并获取每个记录在“范围”内存在的最大data_total_x值。

我的预期输出类似于以下内容:

代码语言:javascript
运行
复制
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

包含示例数据的sample及其尝试:http://sqlfiddle.com/#!6/ba5a53/10/0

如能提供任何协助,将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-07 18:46:57

我认为这应该可以做到:

代码语言:javascript
运行
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29498755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档