SQL顺序由两个不同(可能为null)的列组成

时间:2022-07-19 22:48:02

I have a table with three columns; the first column contains IDs and the other two columns contain dates (where at most one is null, but I don't think this should affect anything). How would I go about ordering the IDs based on which date is larger? I've tried

我有一个有三列的桌子;第一列包含ID,另外两列包含日期(其中最多一列为null,但我认为这不会影响任何事情)。我如何根据哪个日期更大来订购ID?我试过了

ORDER BY CASE
WHEN date1 > date2 THEN date1
ELSE date2
END

but this didn't work. Can anyone help me? Also, all of the similar problems that I've seen others post have it so that the query sorts the results based on the first column, and then if the first column is null, the second column. Would I first have to define every single null value? I'm creating this table by a full outer join, so that would be an entirely different question to ask, so hopefully it can be done with null values.

但这没用。谁能帮我?此外,我见过其他人发布的所有类似问题都有它,以便查询根据第一列对结果进行排序,然后如果第一列为空,则为第二列。我首先必须定义每个空值吗?我正在通过完全外部联接创建此表,因此这将是一个完全不同的问题,所以希望它可以使用空值来完成。

2 个解决方案

#1


15  

I believe your problem is related to the comparison failing when either column is NULL. So, you probably need:

我相信你的问题与任何列为NULL时的比较失败有关。所以,你可能需要:

 ORDER BY CASE
          WHEN date1 IS NULL THEN date2
          WHEN date2 IS NULL THEN date1
          WHEN date1 > date2 THEN date1
          ELSE                    date2
          END

#2


-2  

Try...

尝试...

SELECT MAX(date1,date2) date FROM table ORDER BY date;

#1


15  

I believe your problem is related to the comparison failing when either column is NULL. So, you probably need:

我相信你的问题与任何列为NULL时的比较失败有关。所以,你可能需要:

 ORDER BY CASE
          WHEN date1 IS NULL THEN date2
          WHEN date2 IS NULL THEN date1
          WHEN date1 > date2 THEN date1
          ELSE                    date2
          END

#2


-2  

Try...

尝试...

SELECT MAX(date1,date2) date FROM table ORDER BY date;