2

参照:postgresql:注文された結果

私はこの質問をし、答えを受け入れました。さて、聞いた時、頭の中で何か違うことがあったのですが、受け入れられた答えに納得しました。さて、私は最近、受け入れられた答えは私が望んでいたものではないことに気づきました。さて、私は質問を言い換えています:

私は次のようなテーブルを持っています:

 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は1つのグループに配置する必要があり、そのグループの最初の行はis_root=1である必要があります。
  • グループはルートDESCのタイムスタンプに基づいてソートする必要がありますが、ルートの子はASC(タイムスタンプベース)でソートする必要があります。

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

どんな助けでも大歓迎です。

ありがとう

4

1 に答える 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
;

出力サンプルデータは入力と同じではありません。たとえば、入力ID#7のタイムスタンプは190で、出力のタイムスタンプは120です。したがって、このクエリが間違っていると考える前に、出力を確認してください。

于 2011-07-19T00:18:40.037 に答える