2011-07-18 32 views
2

REFER:postgresql: ordered resultPostgreSQL的:爲了結果 - II

我問這個問題,並接受了答案。那麼,在提問的時候,我腦子裏有不同的東西,但我確信接受的答案。那麼,我最近意識到接受的答案不是我想要的。嗯,我重申這個問題:

我有一個表,它看起來像:

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的時間戳進行排序,但是根節點的子節點LD進行排序ASC(基於時間戳)

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

任何幫助理解。

由於

回答

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.因此,在考慮此查詢錯誤之前,請檢查您的輸出。

+0

對不起,輸入錯誤。輸入ID#7應該是120.非常感謝。 – Mayank

+0

+1爲正確的解決方案:) –