如何在sql中首先使用非空值按列排序

时间:2021-12-28 10:18:00

I need to write a sql statement to select all users ordered by lastname, firstname. This is the part I know how to do :) What I don't know how to do is to order by non-null values first. Right now I get this:

我需要编写一个sql语句来选择所有按lastname、firstname排序的用户。这是我知道怎么做的部分:)我不知道怎么做的是先用非空值排序。现在我明白了:

null, null
null, null
p1Last, p1First
p2Last, p2First

null

etc

I need to get:

我需要:

p1Last, p1First
p2Last, p2First
null, null
null, null

p1Last, p1First p2Last, p2First null, null

Any thoughts?

任何想法吗?

2 个解决方案

#1


27  

See Sort Values Ascending But NULLS Last

请参阅升序但最后为空的排序值

basically

基本上

SELECT *
    FROM @Temp
    ORDER BY CASE WHEN LastName IS NULL THEN 1 ELSE 0 END, LastName

#2


10  

ORDER BY CASE WHEN name IS NULL THEN 1 ELSE 0 END, name;

#1


27  

See Sort Values Ascending But NULLS Last

请参阅升序但最后为空的排序值

basically

基本上

SELECT *
    FROM @Temp
    ORDER BY CASE WHEN LastName IS NULL THEN 1 ELSE 0 END, LastName

#2


10  

ORDER BY CASE WHEN name IS NULL THEN 1 ELSE 0 END, name;