0

MySQL - 按字母顺序排列所有数据,但将特定项目放在最后

这个问题已经被问到了 MySql,不幸的是这个解决方案不适用于 SQL Server。这是我当前的查询和结果:

select ShipMethodID As UseMe, Name As ShowMe 
from Purchasing.ShipMethod
union
Select 0 As UseMe, 'n/a' As ShowMe
order by ShowMe

结果:

5   CARGO TRANSPORT 5
0   n/a
4   OVERNIGHT J-FAST
3   OVERSEAS - DELUXE
1   XRQ - TRUCK GROUND
2   ZY - EXPRESS

我需要像这样进行排序:

0   n/a
5   CARGO TRANSPORT 5
4   OVERNIGHT J-FAST
3   OVERSEAS - DELUXE
1   XRQ - TRUCK GROUND
2   ZY - EXPRESS
4

3 回答 3

4
select * from (
    select ShipMethodID As UseMe, Name As ShowMe 
    from Purchasing.ShipMethod
    union
    Select 0 As UseMe, 'n/a' As ShowMe
) t
order by (case when UseMe = 0 then null else ShowMe end)
于 2013-02-27T13:18:51.630 回答
3

首先按一个字段排序,以便首先获得 N/A,然后按您真正想要排序的字段 - 如果您真的想要 n/a last then order by DisplayOrder DESC, ShowMe

select      ShipMethodID As UseMe, Name As ShowMe, 1 AS DisplayOrder
from        Purchasing.ShipMethod
union
Select      0 As UseMe, 'n/a' As ShowMe, 0 AS DisplayOrder
order by    DisplayOrder, ShowMe
于 2013-02-27T13:21:39.207 回答
2

请尝试使用此查询..

select ShipMethodID As UseMe, Name As ShowMe, 1 As dummycolumn
from Purchasing.ShipMethod
union
Select 0 As UseMe, 'n/a' As ShowMe, 0 As dummycolumn
order by dummycolumn, ShowMe
于 2013-02-27T13:22:27.377 回答