postgresql-SQL-`true`值的计数 [英] postgresql - sql - count of `true` values

查看:235
本文介绍了postgresql-SQL-`true`值的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

myCol
------
 true
 true
 true
 false
 false
 null

在上表中,如果我这样做:

In the above table, if I do :

select count(*), count(myCol);

我得到 6,5

我得到 5 ,因为它不计算空条目。

I get 5 as it doesn't count the null entry.

我还如何计算真实值的数量(示例中为3)?

How do I also count the number of true values (3 in the example)?

(这是一个简化,实际上我使用的是更复杂的值计数函数中的表达式)

(This is a simplification and I'm actually using a much more complicated expression within the count function)

编辑摘要:我也想在查询中包括一个普通count(*),所以不能使用where子句

Edit summary: I also want to include a plain count(*) in the query, so can't use a where clause

推荐答案

SELECT COALESCE(sum(CASE WHEN myCol THEN 1 ELSE 0 END),0) FROM <table name>

或者,如您所知:

SELECT count(CASE WHEN myCol THEN 1 END) FROM <table name>

这篇关于postgresql-SQL-`true`值的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆