代码之家  ›  专栏  ›  技术社区  ›  Sigularity

如何对每个组的行进行排序(PostgreSQL)

  •  0
  • Sigularity  · 技术社区  · 9 年前

    有一个组编号,每个组有几个inst编号。 我想到了联合,但我看不出正确的一个。

    在这件事上你能帮我吗?

    @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 回复  |  直到 9 年前
        1
  •  2
  •   Clodoaldo Neto    9 年前
    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 如果条件在组的任何行中为true,则为true。