PostgreSQL:使用别名列时的情况

标签 postgresql

我想做这样的事情:

select 
case when (select count(*) as score from users t1 )   >5   THEN score   else 0 end 

当我尝试时出现错误:

column score doesn't exists. 

我可以用其他方式做到这一点吗?我需要它来设置一个 LIMIT 值。我当然想这样做:

select 
case when (select count(*) as score from users t1 )   >5   THEN (select count(*) as score from users)    else 0 end 

但我需要执行两次相同的查询。 有人有想法吗?

最佳答案

您可以使用 WITH 子句:

with a as (select count(*) score from t)
select case when score > 5 then score else 0 end from a;

或子查询(内联 View ):

select case when score > 5 then score else 0 end 
from (select count(*) score from t) t;

关于PostgreSQL:使用别名列时的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17265151/

相关文章:

postgresql - 在具有 ID 的多个列中查找具有相同值的行

postgresql - SQL - 分组依据 - 限制子句 - postgresql

postgresql - 为什么我在运行 top 时看到 postgres 进程,尽管它只在 Docker 内部运行?

postgresql - 在 slave postgres 数据库上查看

postgresql - 如何复制与数据库服务器相同的环境配置?

php - Doctrine - 按外部聚合值过滤

java - 我如何为 postgreSQL 创建服务器端应用程序(适用于 Android 应用程序,没有 Firebase)

python - 使用 sqlalchemy 等待行更新或行插入

postgresql - centos5 postgresql客户端

ruby - 如何使pg gem查询结果符号化?