从SQL中的主查询中提取子集

问题描述 投票:0回答:1

在下面的查询中,我将“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

想知道我是否可以在上面的查询中找到子查询来查找一个月内活跃的客户。任何建议都会很棒。

sql hive
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.