有一個組號碼,每個組有幾個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"
'''按group_number desc,inst_number'''順序排列?.. –
否。當只有一個組的狀態是'ABNORMAL'時,它應該首先打印在上面。 – Sigularity
請用'INSERT INTO test.sort_test VALUES(0,4,'ABNORMAL')更新帖子''並用新數據更新樣本 –