【问题标题】:Postgresql: Calculate rank by number of true OR clausesPostgresql:按真 OR 子句的数量计算排名
【发布时间】:2012-04-29 22:20:45
【问题描述】:

我需要按正确的 OR 子句的数量对 PostgreSQL 查询的结果进行排序/排名。例如,给定一个类似

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

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

【问题讨论】:

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


    【解决方案1】:

    重复条件并添加它们:

    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
    

    【讨论】:

      【解决方案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
      

      这个解决方案的丑陋之处在于你在语句中每个条件都有两次,但我现在想不出另一种解决方案。

      【讨论】:

      • 可以省略CASE关键字吗?
      • @a_horse_with_no_name:我认为用户不想聚合。只需将 CASE 语句相加即可。您还可以剥离子选择并将表达式放入 ORDER BY 子句中。
      【解决方案3】:
      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.
      

      【讨论】:

        猜你喜欢
        • 2012-08-30
        • 1970-01-01
        • 1970-01-01
        • 2014-10-12
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多