我试图按字母顺序按值对每一列进行排序,然后再按NULL 。但是,它不起作用。我试图在完全加入之前在每个查询中按顺序排列,但是这不允许这样做,那么达到目标的可能方法有哪些?
Select t1.Name AS Doctor, t2.Name AS Professor, t3.Name AS Singer,t4.Name AS Actor
FROM (
SELECT Name
FROM Occupation
Where Occupation ='Doctor'
) t1
FULL JOIN
(
SELECT Name
FROM Occupation
Where Occupation ='Professor'
) t2
on t1.Name=t2.Name
FULL JOIN
(
SELECT Name
FROM Occupation
Where Occupation ='Singer'
) t3
on t1.Name=t3.Name
FULL JOIN
(
SELECT Name
FROM Occupation
Where Occupation ='Actor'
) t4
on t1.Name=t4.Name
ORDER BY Doctor ASC, Professor ASC, Singer ASC, Actor ASC
错误的结果:
Doctor Professor Singer Actor
-------------------------------------------
NULL NULL NULL Jane
NULL NULL NULL Julia
NULL NULL NULL Maria
NULL NULL Meera NULL
NULL NULL Priya NULL
NULL Ashley NULL NULL
NULL Christeen NULL NULL
NULL Ketty NULL NULL
Jenny NULL NULL NULL
Samantha NULL NULL NULL
预期结果:
Doctor Professor Singer Actor
-------------------------------------------
Jenny Ashley Meera Jane
Samantha Christeen Priya Julia
NULL Ketty NULL Maria
NULL NULL NULL NULL
NULL NULL NULL NULL
NULL NULL NULL NULL
NULL NULL NULL NULL
NULL NULL NULL NULL
NULL NULL NULL NULL
NULL NULL NULL NULL
答案 0 :(得分:4)
使用CASE
,如果该值为空,则返回的值要大于不为空的值。
...
ORDER BY CASE
WHEN doctor IS NULL THEN
1
ELSE
0
END,
doctor,
CASE
WHEN professor IS NULL THEN
1
ELSE
0
END,
professor,
CASE
WHEN singer IS NULL THEN
1
ELSE
0
END,
singer,
CASE
WHEN actor IS NULL THEN
1
ELSE
0
END,
actor
答案 1 :(得分:1)
您可以使用
ORDER BY isnull(Doctor, 'zzzzzzzzzzzzzzz') ASC
, isnull(Professor, 'zzzzzzzzzzzzzzz') ASC
, isnull(Singer, 'zzzzzzzzzzzzzzz') ASC
, isnull(Actor, 'zzzzzzzzzzzzzzz') ASC
答案 2 :(得分:1)
您也可以尝试
order by case when Column is not null then Column else Replicate(char(255),Len(255)) end
您用列的精确长度替换 Len(255)中的255。
我认为这是最可靠的解决方案,因为如果数据库值'z'中的所有ascii字符均为122,则用户可能会使用例如。 '(',这会弄乱您的排序。
但是如果您没有这种极端的情况,Milad Aghamohammadi的anwser也可以,而且简单得多