Return 活动记录与非活动记录根据单个列中的给定日期计数

Return active vs inactive records count against a given date in a single column

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

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)和 'Inactive' = 2(第一个日期的 0 +1 从第二次约会开始) 而 'TotalCount' 值是准确的。

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

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

我在这里做错了什么? 什么是正确的查询?我目前正在 Databricks Delta Lake SQL.

中执行这些操作

我不确定数据块,但我认为这应该可行...

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)

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