Home > OS >  How to order rows by the greatest date of each row, for a table with 8 date columns?
How to order rows by the greatest date of each row, for a table with 8 date columns?

Time:05-23

This is very different from doing an SQL order by 2 date columns (or for proper way to sort sql columns, which is only for 1 column). There, we would do something like:

ORDER BY CASE WHEN date_1 > date_2 
         THEN date_2 ELSE date_1 END

FYI, I'm using YYY-MM-DD in this example for brevity, but I also need it to work for TIMESTAMP (YYYY-MM-DD HH:MI:SS)

I have this table:

id name date_1 date_2 date_3 date_4 date_5 date_6 date_7 date_8
1 John 2008-08-11 2008-08-12 2009-08-11 2009-08-21 2009-09-11 2017-08-11 2017-09-12 2017-09-30
2 Bill 2008-09-12 2008-09-12 2008-10-12 2011-09-12 2008-09-13 2022-05-20 2022-05-21 2022-05-22
3 Andy 2008-10-13 2008-10-13 2008-10-14 2008-10-15 2008-11-01 2008-11-02 2008-11-03 2008-11-04
4 Hank 2008-11-14 2008-11-15 2008-11-16 2008-11-17 2008-12-31 2009-01-01 2009-01-02 2009-01-02
5 Alex 2008-12-15 2018-12-15 2018-12-15 2018-12-16 2018-12-17 2018-12-18 2018-12-25 2008-12-31

... But, the permutations of that give me a headache, just to think about them.

This Answer had more of a "general solution", but that was to SELECT, not to ORDER BY...

SELECT MAX(date_col)
FROM(
  SELECT MAX(date_col1) AS date_col FROM some_table
  UNION
  SELECT MAX(date_col2) AS date_col FROM some_table
  UNION
  SELECT MAX(date_col3) AS date_col FROM some_table
  ...
)

Is there something more like that, such as could be created by iterating a loop in, say PHP or Node.js? I need something a scalable solution.

  • I only need to list each row once.
  • I want to order them each by whichever col has the most recent date of those I list on that row.

Something like:

SELECT * FROM some_table WHERE
(
  GREATEST OF date_1
  OR date_2
  OR date_3
  OR date_4
  OR date_5
  OR date_6
  OR date_7
  OR date_8
)

CodePudding user response:

You can use the GREATEST function to achieve it.

SELECT  GREATEST(date_1,date_2,date_3,date_4,date_5,date_6,date_7,date_8) max_date,t.*
FROM Tab t
ORDER BY GREATEST(date_1,date_2,date_3,date_4,date_5,date_6,date_7,date_8) Desc;

DB Fiddle: Try it here

max_date id name date_1 date_2 date_3 date_4 date_5 date_6 date_7 date_8
2022-05-22 2 Bill 2008-09-12 2008-09-12 2008-10-12 2011-09-12 2008-09-13 2022-05-20 2022-05-21 2022-05-22
2018-12-25 5 Alex 2008-12-15 2018-12-15 2018-12-15 2018-12-16 2018-12-17 2018-12-18 2018-12-25 2008-12-31
2017-09-30 1 John 2008-08-11 2008-08-12 2009-08-11 2009-08-21 2009-09-11 2017-08-11 2017-09-12 2017-09-30
2009-01-02 4 Hank 2008-11-14 2008-11-15 2008-11-16 2008-11-17 2008-12-31 2009-01-01 2009-01-02 2009-01-02
2008-11-04 3 Andy 2008-10-13 2008-10-13 2008-10-14 2008-10-15 2008-11-01 2008-11-02 2008-11-03 2008-11-04
  • Related