【发布时间】: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