计数多个列的单词

时间:2014-01-24 15:14:01

标签: sql select count distinct

我正在尝试计算一个单词在Select语句的不同列中出现的频率。 例如:

column1  column2  column3
No       No       No
Yes      Yes      No
Yes      No       Yes
Yes      Yes      Yes

因此,如果我在“是”这个词之后搜索,结果将是:

count1  count2  count3
3       2       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;