【问题标题】:Count word over multiple columns [closed]计算多列的单词[关闭]
【发布时间】:2014-02-15 15:33:26
【问题描述】:
我试图计算一个单词在 Select 语句的不同列中出现的频率。
例如:
column1 column2 column3
No No No
Yes Yes No
Yes No Yes
Yes Yes Yes
所以如果我在“是”这个词之后搜索,结果会是这样的:
count1 count2 count3
3 2 2
有人可以帮我吗?
【问题讨论】:
标签:
sql
select
count
distinct
【解决方案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
这是可行的,因为如果不满足条件,case 将返回 NULL 值。聚合忽略 NULL 值,因此 count() 只会计算 yes 值。
【解决方案2】:
当一列包含 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;