Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GROUP BY with MAX and UNION, or JOIN?

How to obtain from this table date_departure and date_arrival for each travel according visiting_order

select * from step;
 id_step | id_travel | id_port | visiting_order | date_arrival | date_departure 
---------+-----------+---------+----------------+--------------+----------------
       1 |         1 |       1 |              0 |              | 2021-01-12
       2 |         1 |       2 |              1 | 2021-05-20   | 2021-05-22
       3 |         1 |       3 |              2 | 2021-07-27   | 
       4 |         2 |       4 |              0 |              | 2021-02-13
       5 |         2 |       5 |              1 | 2021-02-27   | 
       6 |         3 |       7 |              0 |              | 2022-01-12
       7 |         3 |       6 |              1 | 2022-05-27   | 

like this :

  id_travel | date_departure | date_arrival
------------+----------------+--------------
          1 |   2021-01-12   |  2021-07-27              
          2 |   2021-02-13   |  2021-02-27              
          3 |   2022-01-12   |  2022-05-27  

?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My first intention was to take both columns and UNION them

   (SELECT id_travel, date_departure FROM step WHERE visiting_order = 0 
    GROUP BY id_travel, date_departure)

    UNION

   (SELECT A.id AS id_travel, A.arr_date AS date_arrival FROM 
      (SELECT id_travel, MAX(visiting_order), date_arrival
       FROM step GROUP BY id_travel
      ) AS A(id, ord, arr_date)
   );

and first select is ok

 id_travel | date_departure 
-----------+----------------
         1 | 2021-01-12
         2 | 2021-02-13
         3 | 2022-01-12

but second one return an error

 ERROR:  column "step.date_arrival" must appear in the GROUP BY clause or be used in an aggregate function

>Solution :

Seems like this can just be:

SELECT id_travel
     , min(date_departure) AS date_departure
     , max(date_arrival) AS date_arrival
FROM   step
GROUP  BY 1
ORDER  BY 1;

Certainly works with your sample data.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading