Postgres GROUP BY,然后排序

Day*_*ana 5 sql postgresql group-by aggregate sql-order-by

我有一个数据库查询,如:

SELECT 
  Foo,
  Foo2,
  some_calc as Bar,
  some_other_calc as Bar2,
From
 FooBar
-- some inner joins for the calcs
GROUP BY FOO
ORDER BY Bar DESC, Bar2 DESC;
Run Code Online (Sandbox Code Playgroud)

我想使用 order 查询按数据库排序,然后将FOOs组合在一起,以便第一个分组块包含FOO具有最大 Bar 的块。FOOs的第二个分组块包含秒最高的 Bar 等。

但这不起作用,因为 Postgres 不允许随机分组:

column "Bar" must appear in the GROUP BY clause or be used in an aggregate function.

我怎样才能解决这个问题?

示例数据和输出:

????????????????????????????
? FO  ? Bar      ?  Bar 2  ?
????????????????????????????
?  6  ?     10   ?         ?
?  4  ?     110  ?         ?
?  3  ?     120  ?         ?
?  8  ?     140  ?         ?
?  3  ?     180  ?         ?
?  3  ?     190  ?         ?
????????????????????????????
Run Code Online (Sandbox Code Playgroud)

输出:

????????????????????????????
? FO  ? Bar      ?  Bar 2  ?
????????????????????????????
?  3  ?     190  ?         ?
?  3  ?     180  ?         ?
?  3  ?     120  ?         ?
?  8  ?     140  ?         ?
?  4  ?     110  ?         ?
?  6  ?     10   ?         ?
????????????????????????????
Run Code Online (Sandbox Code Playgroud)

Erw*_*ter 5

SELECT foo, <some calc> AS bar, bar2
FROM   foobar
ORDER  BY max(<some calc>) OVER (PARTITION BY foo) DESC NULLS LAST  -- can't refer to bar
        , bar DESC NULLS LAST  -- but you can here
        , foo DESC NULLS LAST;
Run Code Online (Sandbox Code Playgroud)

bar不必是一列,可以是任何有效的表达式,甚至是聚合函数(与 结合GROUP BY)——只是不是另一个不能嵌套的窗口函数。例子:

但是,您不能在窗口函数内的同一查询级别上引用列别名(输出列名称)。您必须再次拼出表达式,或者将计算移至子查询或 CTE。
可以ORDER BYand 中引用输出列名称GROUP BY(但不能在WHEREorHAVING子句中)。解释:

由于它尚未定义,我们必须期待 NULL 值。通常,您希望最后使用 NULL 值,因此请NULLS LAST按降序添加。看:

假设foo在与bar.