我正在尝试计算一个单词在Select语句的不同列中出现的频率。 例如:
column1 column2 column3
No No No
Yes Yes No
Yes No Yes
Yes Yes Yes
因此,如果我在“是”这个词之后搜索,结果将是:
count1 count2 count3
3 2 2
有人可以帮助我吗?
答案 0 :(得分:1)
select count(case when column1 = 'Yes' then 1 end) as count1,
count(case when column2 = 'Yes' then 1 end) as count2,
count(case when column3 = 'Yes' then 1 end) as count3
from the_table
这是有效的,因为如果不满足条件,案例将返回NULL
值。聚合忽略NULL
个值,因此count()
只会计算yes
个值。
答案 1 :(得分:0)
当列包含COUNT和CASE组合的值时计算:
select
count(case when column1 = 'Yes' then 1 else null end) as count1,
count(case when column2 = 'Yes' then 1 else null end) as count2,
count(case when column3 = 'Yes' then 1 else null end) as count3
from mytable;