当组计数为零而不使用连接时动态指定组 class
dynamically specify group class when group count is zero without using join
好的,所以我得到了一个简单的数据集:
id | condition
INT | boolean
我想按 ID 分组并计算每个条件的数量,包括零。
id | condition | count
1 | TRUE | 17
1 | FALSE | 2
2 | TRUE | 0
2 | FALSE | 15
3 | TRUE | 3
3 | FALSE | 0
... | ... | ...
事实是,有大量的 id,其中有很多只有 TRUE 或 FALSE 条件。
我想在我的汇总 table 中计算 0 个计数。
所以我的问题是,我可以在 Amazon Redshift 中执行此操作,而无需加入另一个 table 吗?怎么样?
您可以有条件地聚合数据并对结果进行逆透视
select t.id, c.condition, c.count
from (
select id, count(case when condition then condition end) ct,
count(case when not condition then condition end) cf
from tbl
group by id
) t
cross join lateral (
values( true, coalesce(ct,0)), (false, coalesce(cf,0))
) c(condition, count)
以上查询使用 LATERAL 来逆透视数据。或者,您可以使用数组。两个 versoins 都没有使用其他表。
select t.id, unnest(array[true, false]) condition, unnest(array[ct,cf]) count
from (
select id, count(case when condition then condition end) ct,
count(case when not condition then condition end) cf
from tbl
group by id) t
order by t.id, condition desc
看看下面的查询是否能解决您的问题。
select id,sum(t) as t, sum(f) as f
from (select id,case when condition='t' then count(id) else 0 end as t,
case when condition='f' then count(id) else 0 end as f
from tbl
group by id,condition) t
group by id
order by id
可以在 dbfiddle example
上验证
好的,所以我得到了一个简单的数据集:
id | condition
INT | boolean
我想按 ID 分组并计算每个条件的数量,包括零。
id | condition | count
1 | TRUE | 17
1 | FALSE | 2
2 | TRUE | 0
2 | FALSE | 15
3 | TRUE | 3
3 | FALSE | 0
... | ... | ...
事实是,有大量的 id,其中有很多只有 TRUE 或 FALSE 条件。
我想在我的汇总 table 中计算 0 个计数。
所以我的问题是,我可以在 Amazon Redshift 中执行此操作,而无需加入另一个 table 吗?怎么样?
您可以有条件地聚合数据并对结果进行逆透视
select t.id, c.condition, c.count
from (
select id, count(case when condition then condition end) ct,
count(case when not condition then condition end) cf
from tbl
group by id
) t
cross join lateral (
values( true, coalesce(ct,0)), (false, coalesce(cf,0))
) c(condition, count)
以上查询使用 LATERAL 来逆透视数据。或者,您可以使用数组。两个 versoins 都没有使用其他表。
select t.id, unnest(array[true, false]) condition, unnest(array[ct,cf]) count
from (
select id, count(case when condition then condition end) ct,
count(case when not condition then condition end) cf
from tbl
group by id) t
order by t.id, condition desc
看看下面的查询是否能解决您的问题。
select id,sum(t) as t, sum(f) as f
from (select id,case when condition='t' then count(id) else 0 end as t,
case when condition='f' then count(id) else 0 end as f
from tbl
group by id,condition) t
group by id
order by id
可以在 dbfiddle example
上验证