sql - 根据行值计算行数

标签 sql postgresql postgresql-9.1

我正在调用一个存储过程,该过程返回一个包含两列的表,一个标识(整数)和一个分数(float4)。整数列将是唯一值。我现在想知道表中有多少行的分数大于/小于具有给定值的标识。我正在努力弄清楚如何在 SQL 中做到这一点。例如,如果它是类似于 PHP 的东西,我会按分数对返回的数据进行排序,找到具有我要查找的标识的行的索引,然后从总行数中减去它。在 PostgreSQL 9.1.15 中,我不确定该怎么做。

SELECT COUNT(*) 
FROM my_stored_proc()
WHERE score > *Score of person with given ident*
ORDER BY score;

最佳答案

如果你只关心ident = 2,你可以这样做:

select sum(case when t.score < t2.score then 1 else 0 end) as LessThan,
       sum(case when t.score > t2.score then 1 else 0 end) as GreaterThan
from table t cross join
     (select t.* from table where ident = 2) t2;

如果您只想引用该表一次(如果访问它很昂贵,您会这样做),您可以使用 CTE 执行上述操作,或者您可以执行以下操作:

select sum(case when score < score2 then 1 else 0 end) as LessThan,
       sum(case when score > score2 then 1 else 0 end) as GreaterThan
from (select t.*,
             max(case when ident = 2 then score end) over () as score2
      from table t
     ) t

关于sql - 根据行值计算行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30360753/

相关文章:

sql - 查看 SQL - 减去日期

mysql - 如何将 "%"符号添加到mysql中的值?

Postgresql ColdFusion CFQuery block

postgresql-9.1 - 如何在 postgresql 中为空单元格设置 IsNullOrEmpty 的条件?

sql - 将具有嵌套连接的高级 SQL 查询转换为 Linq-to-sql

sql - 获取相关文章的高级方法(语义)

PostgreSQL json_agg,并尝试分组依据和排序依据(列必须出现在 GROUP BY 中)

mysql - 为什么 PostgreSQL 在 Windows 上这么慢?

django - 将数据库从 sqlite3 转换为 postgres 时出现加载数据错误

sql - Postgres 过滤,以及一个默认的 sentinal for "where in Array"子句,它将 "where"变成重言式