如何轻松计算特定列是 true
的行数和 false
的行数?
我不能(或者我可以?)使用 count() 运行查询,因为我将此计数嵌入到了 had() 子句中,例如:
.having(func.count(Question.accepted) >
func.count(not_(Question.accepted)))
但是通过上述方式,该函数会计算不等式两边的每一行。
我试过这样的事情
.having(func.count(func.if_(Question.accepted, 1, 0)) >
func.count(func.if_(Question.accepted, 0, 1)))
但我收到一个错误
(似乎它在 postgresql 中不存在)。
如何轻松计算列为 true 和 false 的行数?
最佳答案
在 HAVING
clause 中使用聚合函数是非常合法的,因为 HAVING
消除了组行。可以通过使用 NULL
不计数的属性来实现条件计数:
或者如果使用 PostgreSQL 9.4 or later ,使用 aggregate FILTER
clause :
count(*) FILTER (WHERE something > 0)
您也可以使用 sum of ones (and zeros) 。
PostgreSQL >= 9.4 和 SQLAlchemy >= 1.0.0
使用 filtered aggregate function :
.having(func.count(1).filter(Question.accepted) >
func.count(1).filter(not_(Question.accepted)))
较旧的 PostgreSQL 和/或 SQLAlchemy
“if”的 SQL 模拟是
CASE
expression 或者在这种情况下是 nullif()
函数。它们都可以与 NULL
不计算在内的事实一起使用:from sqlalchemy import case
...
.having(func.count(case([(Question.accepted, 1)])) >
func.count(case([(not_(Question.accepted), 1)])))
或者:
.having(func.count(func.nullif(Question.accepted, False)) >
func.count(func.nullif(Question.accepted, True)))
使用
nullif()
可能有点令人困惑,因为“条件”是您不想计算的。您可以设计一个使条件更自然的表达式,但这留给读者。这两个是更便携的解决方案,但另一方面 FILTER
子句是标准的,虽然没有广泛使用。关于python - bool 列上的 SQLAlchemy func.count,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37328779/