如何以升序最后放置NULL

时间:2018-06-20 15:35:02

标签: sql-server null sql-order-by

我需要对表格进行排序,并且需要在底部显示包含Null的行。每当我运行以下查询

select * from t1 
order by status, date;

在第一行中没有显示空值

+--------+------------+--+

| Status |    Date    |  |
+--------+------------+--+
|      1 | NULL       |  |
|      1 | 2011-12-01 |  |
|      1 | 2011-12-21 |  |
|      2 | NULL       |  |
|      2 | 2005-09-02 |  |
|      3 | 2000-08-07 |  |
|        |            |  |
+--------+------------+--+

这就是我需要的:

+--------+------------+--+
| Status |    Date    |  |
+--------+------------+--+
|      1 | 2011-12-01 |  |
|      1 | 2011-12-21 |  |
|      1 | NULL       |  |
|      2 | 2005-09-02 |  |
|      2 | NULL       |  |
|      3 | 2000-08-07 |  |
|        |            |  |
+--------+------------+--+

我该怎么办?

2 个答案:

答案 0 :(得分:6)

select * from t1 
order by status, 
         date, 
         CASE WHEN date is NULL 
              THEN 1
              ELSE 0
         END;

答案 1 :(得分:0)

这项工作是否会进行:order by col asc nulls last