是否有不同的方法将一个项目浮动到已排序的名称列表的顶部?

时间:2012-06-26 22:50:14

标签: sql tsql sql-server-2008-r2

这就是我想到的将“默认”浮动到顶部并对其余部分进行排序:

SELECT        'default' AS name, 'AAA' AS tag
UNION
SELECT        name, name AS tag
FROM            (SELECT DISTINCT TOP (100) PERCENT name
                          FROM            AccountManager
                          WHERE        (name <> 'default')
                          ORDER BY name) AS derivedtbl_1
ORDER BY tag

是否有一种不那么复杂/更好的方式?

2 个答案:

答案 0 :(得分:3)

SELECT name 
FROM AccountManager
GROUP BY name /*To retain DISTINCT semantics from original query*/
ORDER BY CASE WHEN name = 'default' THEN 0 ELSE 1 END, name

注意:

SELECT DISTINCT name 
FROM AccountManager
ORDER BY CASE WHEN name = 'default' THEN 0 ELSE 1 END, name

会因ORDER BY items must appear in the select list if SELECT DISTINCT is specified.因使用GROUP BY

而失败

答案 1 :(得分:1)

您可以更改排序方式:

select name
from AccountManager
order by case name when 'default' then 0 else 1 end, name