[英]BigQuery : case when expression to Count from Same column but different conditions
I have a table with 2 columns as below: 我有一个包含2列的表格,如下所示:
Col 1 | col_stats
Field 1 | open
Field 2 | close
Field 1 | close
Field 1 | open
I want the ouput to be as : 我希望输出为:
Col1 | cnt_open | Cnt_close
Field 1 | 2 | 1
Field 2 | 0 | 1
**I wrote a query ** **我写了一个查询**
select col 1, count(case when col_stats= 'open' then 1 else 0 END) cnt_open,
count (case when col_stats= 'close' then 1 else 0 END ) cnt_close
from `project.dataset.tablename`
group by col1
Resultant output from above query is incorrect: 以上查询的结果输出不正确:
Col1 | cnt_open | Cnt_close
Field 1 | 2 | 2
Field 2 | 1 | 1
Can somebody let me know why the output is giving incorrect result for count even after case condition is applied? 有人可以让我知道为什么即使应用了条件条件后,输出仍给出错误的结果以计数吗?
Use countif()
: 使用
countif()
:
select col1, countif(col_stat = 'open') as num_opens, countif(col_stat = 'closed') as num_closes
from t
group by col1;
In SQL count()
counts the number of non- NULL
values. 在SQL中,
count()
计算非NULL
值的数量。 Your code would work with sum()
. 您的代码将与
sum()
。 But countif()
is simpler and clearer. 但是
countif()
更简单明了。
Use null
instead of 0
: 使用
null
而不是0
:
select col1, count(case when col_stats= 'open' then 1 else null END) cnt_open,
count (case when col_stats= 'close' then 1 else null END ) cnt_close
from `project.dataset.tablename`
group by col1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.