SQL:过去x个月每个客户的平均应用程序数

时间:2015-03-04 11:37:12

标签: sql sql-server

我有3个表Customer,Applications,ApplicationHistory。我必须检索以下数据:

  1. 获取过去3个月内每位客户的平均申请数
  2. 获取过去3个月内至少有一个或多个申请的客户数量
  3. 我一直在尝试小组,但有以下问题:

    • ApplicationHistory表为每个应用程序提供了多个条目,现在确定如何消除它们&

    • 注意:已将Customer Table包含为按客户类型

    • 过滤数据的需要

    你能否建议我怎样才能做到这一点?

    非常感谢,

      

    我的解决方案(不起作用)

    SELECT a.ApplicationId, a.CustomerId,  count(*) count                           
    from [application] a
    inner join [applicationhistory] ah on a.ApplicationId = ah.ApplicationId
    inner join Customer c  on c.CustomerId = a.CustomerId
    where  ah.EventDate between @StartDateFilter and @EndDateFilter 
           --c.CustomerType in ( A, B)
    group by a.ApplicationId, a.CustomerId
    
      

    表格结构:

    Customer
    Name  CustomerId   CustomerType
    test1   1               A
    test2   2               B
    
    Applications
    ApplicationId  CustomerId
    3                   1
    4                   1
    5                   2                
    6                   2                
    7                   2                
    
    ApplicationHistory
    ApplicationId   EventDate         EventType
    3               2014-12-01           New
    3               2014-12-01           Updated
    3               2014-12-02           Withdrawn
    4               2014-12-02           New
    4               2014-12-03           Updated
    5               2014-12-05           New
    5               2014-12-06           Updated
    5               2014-12-06           Updated
    5               2014-12-07           Updated
    6               2014-12-08           New
    

1 个答案:

答案 0 :(得分:1)

首先,您查询并不需要联接 - 除非您关心没有应用程序的客户。所以,这是一个更简单的版本来获得总数

select ah.CustomerId, count(*) as cnt                           
from applicationhistory ah
where  ah.EventDate between @StartDateFilter and @EndDateFilter 
group by a.CustomerId;

请注意,group by只有CustomerId而不是ApplicationId

如果你只想要" New"应用程序,使用where

select ah.CustomerId, count(*) as cnt                           
from applicationhistory ah
where ah.EventDate between @StartDateFilter and @EndDateFilter and
      EventType = 'New'
group by a.CustomerId;

如果你想要网络应用程序" new" - "撤回",然后使用条件聚合:

select ah.CustomerId,
       sum(case when EventType = 'New' then 1 else -1 end) as cnt                   
from applicationhistory ah
where ah.EventDate between @StartDateFilter and @EndDateFilter and
      EventType in ( 'New', 'Withdrawn' )
group by a.CustomerId;