计算 SQL 中 string_agg 之后每一行中的每个值
Count each values in each row after string_agg in SQL
我有一个 SQL table 最后有一列。我按 id 和 string_agg 标题分组。
ID Title
1 a
1 a
1 b
2 c
2 a
我现在有这个table。
Titles
a,a,b
c,a
我想将字符串 agg 中每一行的每个值都计为一个新列。我尝试了 count distinct 或 Count("a") ,它返回一行中所有值的计数。我的预期结果是
Titles count_a count_b count_c count_all
a,a,b 2 1 0 3
c,a 1 0 1 2
这可以在 SQL 中计算吗?
您可以使用条件聚合:
select id, string_agg(title, ',' order by title) as titles,
countif(title = 'a') as num_as,
countif(title = 'b') as num_bs,
countif(title = 'c') as num_cs,
count(*) as total
from t
group by id;
我有一个 SQL table 最后有一列。我按 id 和 string_agg 标题分组。
ID Title
1 a
1 a
1 b
2 c
2 a
我现在有这个table。
Titles
a,a,b
c,a
我想将字符串 agg 中每一行的每个值都计为一个新列。我尝试了 count distinct 或 Count("a") ,它返回一行中所有值的计数。我的预期结果是
Titles count_a count_b count_c count_all
a,a,b 2 1 0 3
c,a 1 0 1 2
这可以在 SQL 中计算吗?
您可以使用条件聚合:
select id, string_agg(title, ',' order by title) as titles,
countif(title = 'a') as num_as,
countif(title = 'b') as num_bs,
countif(title = 'c') as num_cs,
count(*) as total
from t
group by id;