Postgres GROUP BY,然后排序

时间:2016-04-18 21:57:39

标签: sql postgresql group-by sql-order-by aggregate

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

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;

我希望按订单查询按数据库排序,然后将FOO组合在一起,以便第一个分组的块包含具有最大条形的FOOFOO s的第二个分组块包含最高秒数等等。

但是这并不起作用,因为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  ║         ║
╚═════╩══════════╩════╩════╩

输出:

╔═════╦══════════╦════╦════╦
║ FO  ║ Bar      ║  Bar 2  ║
╠═════╬══════════╬═════════╬
║  3  ║     190  ║         ║
║  3  ║     180  ║         ║
║  3  ║     120  ║         ║
║  8  ║     140  ║         ║
║  4  ║     110  ║         ║
║  6  ║     10   ║         ║
╚═════╩══════════╩════╩════╩

3 个答案:

答案 0 :(得分:4)

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;

答案 1 :(得分:3)

你只想要order byGroup by通过聚合减少(通常)行数。

您可以使用窗口功能完成此操作:

SELECT Foo, Bar, Bar2,
From FooBar
ORDER BY MAX(Bar) OVER (PARTITION BY Foo) DESC,
         Foo;

答案 2 :(得分:1)

这不应该做你要求的吗?

如果没有,如果您可以在查询中提供一些示例数据并显示您希望如何将其作为输出,那将会有所帮助。

SELECT 
  Foo,
  MAX(some_calc) as Bar,
  MAX(some_other_calc) as Bar2,
From
 FooBar
##some inner joins for the calcs
GROUP BY FOO;