我的问题与此问题相反。
TSQL - Is it possible to define the sort order?
我想从SQL Server数据库返回一些记录,根据列的值按升序排序但两个特定的记录应该总是在最后。
原始SQL(需要更改)如下:
select code_id as CategoryID, code_desc as CategoryDescription
from codes
where code_id > '000001' and code_id < '000100'
order by CategoryDescription
结果以
的形式返回我想要下面的结果(前两个带有星号的星号):
我尝试了下面的UNION语句,但结果集按升序自动排序,默认情况下这两行都在开头。
select code_id as CategoryID, code_desc as CategoryDescription
from codes
where code_id > '000003' and code_id < '000100'
--order by categoryDescription
UNION
select code_id as CategoryID, code_desc as CategoryDescription
from codes
where code_id > '000001' and code_id < '000004'
答案 0 :(得分:1)
如果您希望维持联盟,那么您可以这样做:
select * from (
select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription, 1 as order
from codes
where code_id > '000003' and code_id < '000100'
UNION
select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription, 2 as order
from codes
where code_id > '000001' and code_id < '000004'
) x
order by x.order
答案 1 :(得分:0)
select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription
from codes
where (code_id > '000003' and code_id < '000100') or (code_id > '000001' and code_id < '000004')
按code_id desc排序
您的代码太长,为什么不将其更改为此?
答案 2 :(得分:0)
你可能正在寻找这个
select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription
from codes
where (code_id > '000003' and code_id < '000100') OR
(code_id > '000001' and code_id < '000004')
ORDER BY CASE
WHEN (code_id > '000003' and code_id < '000100') THEN 1
WHEN (code_id > '000001' and code_id < '000004') THEN 2
END