2017-08-24 41 views
0

有一個組號碼,每個組有幾個inst號碼。 我需要根據狀態值對查詢結果進行排序。 如果組內狀態列的值爲'ABNORMAL',則屬於該組的總行應打印在上面,就像所需的結果一樣。 我想到了聯盟所有,但我沒有看到正確的。如何爲每個組排序(PostgreSQL)

你能幫我解決這個問題嗎?

@ DDL/DML

CREATE TABLE test.sort_test 
(
    group_number integer, 
    inst_number integer, 
    status1 character varying, 
    status2 character varying  
); 

INSERT INTO test.sort_test VALUES(0,0,'NORMAL','NORMAL'); 
INSERT INTO test.sort_test VALUES(0,1,'NORMAL','NORMAL'); 
INSERT INTO test.sort_test VALUES(0,2,'NORMAL','NORMAL'); 
INSERT INTO test.sort_test VALUES(0,3,'NORMAL','NORMAL'); 
INSERT INTO test.sort_test VALUES(1,0,'ABNORMAL','NORMAL'); 
INSERT INTO test.sort_test VALUES(1,1,'NORMAL','NORMAL'); 
INSERT INTO test.sort_test VALUES(1,2,'NORMAL','NORMAL'); 
INSERT INTO test.sort_test VALUES(2,0,'NORMAL','ABNORMAL'); 

@原始查詢

select * 
from test.sort_test 
order by group_number, inst_number 

0 0 "NORMAL" "NORMAL" 
0 1 "NORMAL" "NORMAL" 
0 2 "NORMAL" "NORMAL" 
0 3 "NORMAL" "NORMAL" 
1 0 "ABNORMAL" "NORMAL" 
1 1 "NORMAL" "NORMAL" 
1 2 "NORMAL" "NORMAL" 
2 0 "NORMAL" "ABNORMAL" 

@期望的結果

1 0 "ABNORMAL" "NORMAL" 
1 1 "NORMAL" "NORMAL" 
1 2 "NORMAL" "NORMAL" 
2 0 "NORMAL" "ABNORMAL"   
0 0 "NORMAL" "NORMAL" 
0 1 "NORMAL" "NORMAL" 
0 2 "NORMAL" "NORMAL" 
0 3 "NORMAL" "NORMAL"  
+1

'''按group_number desc,inst_number'''順序排列?.. –

+0

否。當只有一個組的狀態是'ABNORMAL'時,它應該首先打印在上面。 – Sigularity

+0

請用'INSERT INTO test.sort_test VALUES(0,4,'ABNORMAL')更新帖子''並用新數據更新樣本 –

回答

2
select group_number, inst_number, status1, status2 
from 
    sort_test 
    inner join (
     select group_number, bool_or('ABNORMAL' in (status1, status2)) as abnormal 
     from sort_test 
     group by group_number 
    ) s using (group_number) 
order by not abnormal, group_number, inst_number 
; 
group_number | inst_number | status1 | status2 
--------------+-------------+----------+---------- 
      1 |   0 | ABNORMAL | NORMAL 
      1 |   1 | NORMAL | NORMAL 
      1 |   2 | NORMAL | NORMAL 
      2 |   0 | NORMAL | ABNORMAL 
      0 |   0 | NORMAL | NORMAL 
      0 |   1 | NORMAL | NORMAL 
      0 |   2 | NORMAL | NORMAL 
      0 |   3 | NORMAL | NORMAL 

bool_or爲真,如果在條件中任一爲真該組的行。

+0

太棒了!如果有幾個狀態如status1和status2會怎麼樣?我幾乎瞭解你的解決方案,但不確定有多種因素的bool_or用法。你能幫助我嗎?我相應地編輯了我的問題。 – Sigularity

+0

@Sigularity:兩個狀態的權重是相同還是status1是第一個? –

+0

重量相同。如果任何狀態值爲「異常」,則其組應位於上方。謝謝。 – Sigularity

相關問題