【问题标题】:Count customers the first time they appear计算客户第一次出现的时间
【发布时间】:2016-05-26 10:34:15
【问题描述】:

您好,我需要计算按卖家(创建者)分组的 subcategory=E 的客户数量。一旦某个客户被某个卖家统计,其他卖家就应该无法统计该客户,即使可能存在观察结果。

例子

id  customerID  CreatedBy   createdate  subcategory
1   1111111111  EVAJEN      2014-03-14  E                                          
2   1111111111  MICMAD      2014-04-15  E
3   9999999999  MICMAD      2014-02-10  E`

这里 MICMAD 不应该计算 id=2,因为 EVAJEN 已经向该客户进行了销售。现在我的代码看起来像这样,但我无法检查客户是否已经被计算在内。

sel createdby, cast(createdate  as date) as date1, count(distinct customerID)
from MyDatabase
where  subcategory='E' 
group by 1,2`

谢谢

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题。

标签: sql count teradata


【解决方案1】:

使用子查询来获取第一个日期并计算它。在大多数数据库(包括 Teradata)中,您可以使用窗口函数来获取每个客户的第一行:

select createdby, cast(createdate as date) as date1, count(*)
from (select t.*,
             row_number() over (partition by customerId order by createddate asc) as seqnum 
      from MyDatabase t
      where subcategory = 'E' 
     ) t
where seqnum = 1
group by createdby, cast(createdate as date) ;

【讨论】:

  • 不应该是 row_number() over (partition by customerId order by createddate ASC)吗?
【解决方案2】:

您可以使用 ROW_NUMBER 为每位客户获取一行:

select createdby, cast(createdate as date) as date1, count(*)
from
 (
   select *
   from tab
   where subcategory = 'E' 
   qualify row_number() -- 1st row per customer
           over (partition by customerId 
                 order by createddate) = 1 
     ) t
group by 1,2;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多