首页 > 解决方案 > 使用多个标准对分区进行排序

问题描述

我尝试使用几个标准对分区进行排序。

使用此查询,我有以下输出:

SELECT id, aggregate_id, aggregate_update, detection_time
FROM report.report_table R1
WHERE table_name NOT LIKE 'AGGREGATE_ALERT_EVENT'
ORDER BY MAX(aggregate_update)
OVER (PARTITION BY aggregate_id) ASC,
  aggregate_id, aggregate_update asc, detection_time desc;

按聚合更新而不是检测时间排序的分区

我们看到行是由aggregate_id 分区的。在每个分区内,行首先按aggregate_update ASC 排序,然后按detection_time DESC 排序。但是,分区仅按 MAX(aggregate_update) 排序,我希望分区按 MAX(aggregate_update) 和 MAX(detection_time) DESC 排序。我尝试得到以下结果:

按聚合更新但和检测时间排序的分区

如何使用多个标准对分区本身进行排序?

标签: postgresqlpostgresql-8.4

解决方案


我认为这应该给你你想要的行为:

SELECT id, aggregate_id, aggregate_update, detection_time
FROM report.report_table R1
WHERE table_name NOT LIKE 'AGGREGATE_ALERT_EVENT'
ORDER BY
    MAX(aggregate_update) OVER (PARTITION BY aggregate_id),
    MAX(detection_time) OVER (PARTITION BY aggregate_id) DESC,
    aggregate_id,
    detection_time DESC;

aggregate_id如果两组碰巧具有相同的最大更新值,我添加的第二个排序条件会打破平局。在这种情况下,排序会退回到具有较长检测时间的组来决定哪个组先来。


推荐阅读