我正在调用一个存储过程,该过程返回一个包含两列的表,一个标识(整数)和一个分数(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/