Postgresql:按真OR子句的数量计算排名

时间:2012-04-18 13:34:03

标签: postgresql stored-procedures plpgsql ranking postgresql-9.1

我需要按照真实的OR子句的数量对PostgreSQL查询的结果进行排序/排序。例如,给出类似

的查询
SELECT * FROM mytable WHERE cond1 OR cond2 OR cond3 ORDER BY rank DESC

应根据已满足条件的数量对结果进行排名。此外,非常欢迎使用视图/存储过程解决此问题的方法!

3 个答案:

答案 0 :(得分:5)

重复这些条件并添加它们:

SELECT * FROM mytable 
WHERE fld = 'A' OR fldB = CURRENT_DATE OR fldC = 7
ORDER BY
   (fld = 'A')::int + (fldB = CURRENT_DATE)::int + (fldC = 7)::int  
DESC

答案 1 :(得分:2)

这样的事情可能是:

select *
from (
    SELECT * , case when cond1 then 1 else 0 end
             + case when cond2 then 1 else 0 end
             + case when cond3 then 1 else 0 end as cond_count
    FROM mytable 
    WHERE cond1 
       OR cond2 
       OR cond3 
) t
order by cond_count desc

这个解决方案的丑陋之处在于你在声明中有两次条件,但我现在想不到另一种解决方案。

答案 2 :(得分:-2)

The above query will check those conditions from the left side one by one i.e 

if the cond1 is true then 
      return the results order by rank.
if cond1 is false and cond2 is true then
      return the results order by rank.
if cond1 and cond2 both are false but cond3 is true
      returns the results order by rank.
if all conditions are false then no result is returned.     

So in brief it doesn't check all the conditions simultaneously for OR conditions.


Thanks.