我正在调用一个存储过程,该存储过程返回一个包含两列的表,一个ident(整数)和一个score(float4)。整数列将是唯一值。我现在想知道表中有多少行的分数大于/小于具有给定值的ident。我正在努力弄清楚如何在SQL中做到这一点。如果它类似于PHP,我会按分数对返回的数据进行排序,找到具有我要查找的标识的行的索引,然后从总行数中减去该数据,例如。在PostgreSQL 9.1.15中,我不知道该怎么做。
SELECT COUNT(*)
FROM my_stored_proc()
WHERE score > *Score of person with given ident*
ORDER BY score;
答案 0 :(得分:1)
如果你只关心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
答案 1 :(得分:0)
使用窗口功能:
SELECT worse, better
FROM (
SELECT
ident,
COUNT(*) OVER (ORDER BY score ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) worse,
COUNT(*) OVER (ORDER BY score ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) better,
FROM my_stored_proc()
) t
WHERE ident = 2; -- replace with the "ident" you care about
如果按分数排序,这将只计算结果集中高于或低于当前行的行数。
无论如何,Gordon's解决方案可能稍好一些,因为它会考虑ident
从my_stored_proc()
多次返回ident
的可能性,并考虑每个{{1}}最高分。