在下面的查询中,我将在“2017-09-01 00:00:00”和“2017-11-31 23:59:59”之间活跃的客户数量作为cust_90,并且想要添加另一栏,查找“2017-11-01 00:00:00”和“2017-11-31 23:59:59”(整个期间的子集)之间活跃的客户数量。
select custid, count(distinct concat(visit1, visit2)) as cust_90
from test1
where date_time between "2017-09-01 00:00:00" and "2017-11-31 23:59:59"
and custid = '234214124'
group by custid;
示例输出:
CustomerName cust_90 cust_30
David 38 15
想知道我是否可以在上面的查询中找到子查询来查找一个月内活跃的客户。任何建议都会很棒。
答案 0 :(得分:2)
这称为条件聚合,可以使用case
表达式完成。
select custid,
count(distinct concat(visit1, visit2) end) as cust_90,
count(distinct case when to_date(date_time)>='2017-11-01' then concat(visit1, visit2) end) as cust_30
from test1
where date_time >= '2017-09-01' and date_time < '2017-12-01'
and custid = '234214124'
group by custid;