How to have a custom sort order for a union query in Postgres

后端 未结 3 1620
深忆病人
深忆病人 2021-02-13 11:50

With a query like this (simplified for clarity):

SELECT \'East\' AS name, *
FROM events 
WHERE event_timestamp BETWEEN \'2015-06-14 06:15:00\' AND \'2015-06-21 0         


        
相关标签:
3条回答
  • 2021-02-13 12:05

    I'd add an extra column showing the desired ordering, then use ordinal column positions in the ORDER BY, e.g.

    SELECT 1, 'East' AS name, *
    ...
    UNION ALL
    SELECT 2, 'West' AS name, *
    ...
    ORDER BY 1
    

    Note that you probably also want UNION ALL since your added columns ensure that every set in the union must be distinct anyway.

    0 讨论(0)
  • 2021-02-13 12:06

    Wrap it in a derived table (which is what "HINT: .... or move the UNION into a FROM clause" is suggesting)

    select *
    from (
      ... your union goes here ... 
    ) t
    order by
        CASE
            WHEN name='East' THEN 1 
            WHEN name='West' THEN 2
            WHEN name='Both' THEN 3
            ELSE 4
        END;
    
    0 讨论(0)
  • 2021-02-13 12:10

    By adding an extra column for ordering purpose, however it makes the UNION clause to work exactly as a UNION ALL (it does not eliminate duplicate rows from the result).

    0 讨论(0)
提交回复
热议问题