【问题标题】:Return active vs inactive records count against a given date in a single column在单个列中针对给定日期返回活动记录与非活动记录计数
【发布时间】:2021-12-12 20:39:25
【问题描述】:

我目前有以下 UsersData 表,它提供给定特定日期的汇总历史数据:

Date UserID Name isActive
2021-10-01 1 Sam 1
2021-10-01 2 Dan 1
2021-10-08 1 Sam 0
2021-10-08 2 Dan 1

要求

我的要求是创建另一个汇总数据,该数据将在单行中显示上述给定日期的活动与非活动记录。所以像下面这样:

Date Active Inactive Total
2021-10-01 2 0 2
2021-10-08 1 1 2

到目前为止我的 SQL 查询

现在,当我尝试以下单个查询时,它可以正常工作:

select date, count(distinct userid) AS ActiveCount from User where isActive= 1 group by date
select date, count(distinct userid) AS InactiveCount from User where isActive= 0 group by date

但由于我需要在单个行中显示每个日期的统计信息,因此我尝试了以下查询,但这里似乎做错了一些事情:

select
date,
(select count(distinct userid) from User where isActive= 1 group by date) AS Active,
(select count(distinct userid) from User where isActive= 0 group by date) AS Inactive,
count(distinct userid) AS total 
from userdata
group by date
order by date

有了这个,我将非活动和活动记录的输出作为两个结果的总和 - 活动 = 3(第一个日期的 2 + 第二个日期的 1)和“不活动” = 2(第一个日期的 0 + 第二个日期的 1日期) 而“TotalCount”值是准确的。

这是我通过上述查询得到的输出:

Date Active Inactive Total
2021-10-01 3 1 2
2021-10-08 3 1 2

我在这里做错了什么? 什么是正确的查询?我目前正在 Databricks Delta Lake SQL 中执行这些操作。

【问题讨论】:

    标签: sql apache-spark apache-spark-sql


    【解决方案1】:
    select date
        , count(distinct userid) filter (where isActive= 1) AS ActiveCount 
        , count(distinct userid) filter (where isActive= 0) AS InactiveCount 
        , count(distinct userid) Total
    from User 
    group by date 
    

    【讨论】:

    • 接受这个答案,因为这将更适合我对查询的进一步计划更改。
    【解决方案2】:

    我不确定databricks,但我认为这应该可行...

    select date
    , sum(case when isActive=1 then 1 else 0 end) AS ActiveCount 
    , sum(case when isActive=0 then 1 else 0 end) AS InactiveCount 
    , count(distinct userId) as total
    from User 
    group by date
    

    (SQLFiddle)

    【讨论】:

      猜你喜欢
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多