ORDER BY
使用CASE
- 声明
Col1
排序的日期列Col2 DESC
中的空值Col1
按Col1 DESC
排序我试过以下:
SELECT columns FROM tables WHERE condition
ORDER BY
case when Table1.Col1 IS NULL then 0 end, Table2.Col2 DESC,
case when Table1.Col1 IS NOT NULL then 1 end, Table1.Col1 DESC
但排序顺序错误,NOT NULL值是第一个(按Col2而不是Col1排序)。我想我错过了一个细节。
答案 0 :(得分:7)
SELECT columns FROM tables
WHERE condition
ORDER BY
case when Table1.Col1 IS NULL then 0 else 1 end ASC
,case when Table1.Col1 IS NULL then Table2.Col2 else Table1.Col1 end DESC
答案 1 :(得分:4)
这应该有效 - 只需根据它是否为空来使第一列为0或1:
SELECT columns FROM tables WHERE condition
ORDER BY
case
when Table1.Col1 IS NULL then 0
else 1
end,
case
when Table1.Col1 IS NULL then Table1.Col2
else Table1.Col1
end