【问题标题】:How to find Min and Max rows from a table including all columns from postgresql如何从包含 postgresql 的所有列的表中查找最小和最大行
【发布时间】:2020-12-22 19:48:59
【问题描述】:

我有一个视图select c1,c2,count from table,它会在下面给出结果。

我想获取整行的最大和最小计数值,并且应该只返回两行最大和最小计数,如下所示。

怎么做?

【问题讨论】:

    标签: sql postgresql greatest-n-per-group window-functions


    【解决方案1】:

    最快的方法可能是联合:

    (
      select c1, c2, count 
      from the_table
      order by count 
      limit 1
    )
    union all
    (
      select c1, c2, count 
      from the_table
      order by count desc
      limit 1
    )
    

    通常,UNION 中的单个语句不需要括号,但由于我们希望每个语句都有一个 order by,所以它们是必需的。

    另一种选择是连接派生表:

    select t1.*
    from the_table t1
      join (
        select min(count) as min_count, 
               max(count) as max_count
        from the_table
      ) mm on t1.count in (mm.min_count, mm.max_count)
    

    但我怀疑这会更快。

    【讨论】:

    • 以上对单组有帮助。例如。我还有一列,即 C3 和 C3 并不是所有行都是唯一的。但它会重复几行。在这种情况下,我想按 C3 列对行进行分组,并为每组 C3 找到最小最大值。这可能吗???
    • @JohnsonAnthony:一旦你有答案,请不要扩大你的问题范围。看看greatest-n-per-group 的当前答案很可能已经回答了。
    【解决方案2】:

    我会推荐窗口函数:

    select *
    from (
        select t.*,
            row_number() over(order by count) rn_asc,
            row_number() over(order by count desc) rn_desc
        from mytable t
    ) t
    where 1 in (rn_asc, rn_desc)
    order by count
    

    这需要只扫描一次表(而不是union alljoin)。

    【讨论】:

    猜你喜欢
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2018-08-10
    • 2018-03-19
    • 1970-01-01
    • 2020-12-02
    相关资源
    最近更新 更多