对于具有 8 个日期列的 table,如何按每行的最大日期对行进行排序?

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

这与只针对 1 列的 SQL order by 2 date columns (or for proper way to sort sql columns 非常不同)。在那里,我们会做类似的事情:

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

仅供参考,为了简洁起见,我在此示例中使用 YYY-MM-DD,但我也需要它来工作 TIMESTAMP (YYYY-MM-DD HH:MI:SS)

我有这个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

...但是,这些排列让我头疼,只是想想它们。

This Answer 有更多的“通用解决方案”,但那是 SELECT,而不是 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
  ...
)

是否有更类似的东西,比如可以通过迭代循环来创建,比如 PHP 或 Node.js?我需要一个 可扩展的 解决方案。

类似于:

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
)

可以使用GREATEST函数来实现

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

NULL 值的情况下,GREATEST 可以 throw-off ORDER

基于 this Answer 来自关于 GREATEST 处理 NULL 的问题,这将根据批准的答案应用这些表格:

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