PostgreSql:订单结果 - II

问题描述 投票:2回答:1

参考:postgresql: ordered result

我问了这个问题并接受了答案。好吧,在问我脑子里有什么不同的东西时,我被接受的答案说服了。好吧,我最近意识到接受的答案不是我想要的。好吧,我正在重述这个问题:

我的桌子看起来像:

 id | user_id | activity_id | activity_type | root_id | is_root | timestamp 
----+---------+-------------+---------------+---------+---------+-----------
  1 |       1 |           1 | text          |       1 |       1 |       200
  2 |       2 |           2 | text          |       1 |       0 |       206
  3 |       3 |           3 | text          |       1 |       0 |       210
  4 |       2 |          10 | text          |      10 |       1 |        50
  5 |       1 |          11 | text          |      10 |       0 |        90
  6 |       3 |          12 | text          |      10 |       0 |       100
  7 |       3 |          20 | text          |      20 |       1 |       120
  8 |       2 |          21 | text          |      20 |       0 |       130
  9 |       3 |          22 | text          |      20 |       0 |       150
 10 |       3 |          22 | text          |      20 |       0 |       150
 11 |       3 |          22 | text          |      20 |       0 |       190

我正在寻找的输出是:

 id | user_id | activity_id | activity_type | root_id | is_root | timestamp 
----+---------+-------------+---------------+---------+---------+-----------
  1 |       1 |           1 | text          |       1 |       1 |       200
  2 |       2 |           2 | text          |       1 |       0 |       206
  3 |       3 |           3 | text          |       1 |       0 |       210
  7 |       3 |          20 | text          |      20 |       1 |       120
  8 |       2 |          21 | text          |      20 |       0 |       130
 11 |       3 |          22 | text          |      20 |       0 |       150
  9 |       3 |          22 | text          |      20 |       0 |       150
 10 |       3 |          22 | text          |      20 |       0 |       190
  4 |       2 |          10 | text          |      10 |       1 |        50
  5 |       1 |          11 | text          |      10 |       0 |        90
  6 |       3 |          12 | text          |      10 |       0 |       100
  • root_id应该放在一个组中,该组的第一行应该有is_root = 1。
  • 应根据根DESC的时间戳对这些组进行排序,但是根目录的子节点应按ASC(基于时间戳)进行排序

The relevant columns for the question is root_id, is_root, timestamp.

任何帮助表示赞赏。

谢谢

postgresql recursive-query
1个回答
3
投票
select
    id,
    user_id, 
    activity_id,
    activity_type,
    t.root_id,
    is_root,
    timestamp
from t
inner join (
    select root_id, max(timestamp) as root_id_max_timestamp
    from t
    group by root_id
) root_id_timestamp on t.root_id = root_id_timestamp.root_id
order by
    root_id_max_timestamp desc,
    is_root = 1 desc,
    timestamp
;

您的输出样本数据与输入不同。例如,输入标识#7的时间戳为190,而输出标识为120的时间戳。因此,在您认为此查询错误之前,请检查输出。

© www.soinside.com 2019 - 2024. All rights reserved.