您好我需要计算按卖家(createdby)分组的子类别= 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`
由于EVAJEN已经向该客户进行了销售,因此MICMAD不应该计算id = 2。现在我的代码看起来像这样,但我无法检查客户是否已被计算在内。
sel createdby, cast(createdate as date) as date1, count(distinct customerID)
from MyDatabase
where subcategory='E'
group by 1,2`
谢谢
答案 0 :(得分: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) ;
答案 1 :(得分:0)
您可以使用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;