在SQL Server中的自定义顺序

时间:2019-05-17 14:02:02

标签: sql-server tsql sql-server-2017

下面是select语句

select * 
from #final
order by 
    case  
       when [Col1] in (select top 10 [Col1] from #take order by [Col2] desc) 
          then 0
          else 2
    end

我上面的select语句返回如下结果

            Col1                              Col2
            --------------------------------------
            App                              86748
            AppService                         832
            BK                               21227
            Cap                             160272
            Fukusima                          1634
            McBaa                             1727
            Others                            6718

但是,我想得到这个结果:

            Col1                              Col2
            --------------------------------------
            Cap                             160272
            App                              86748
            BK                               21227
            McBaa                             1727
            Fukusima                          1634
            AppService                         832
            Others                            6718

如何实现?谢谢。

2 个答案:

答案 0 :(得分:1)

您只是在两种类型之间进行了区别,但是在该类型0内,没有二阶方法。只需添加Col1作为第二阶,降序即可。

select * from #final
        order by 
        case when [Col1] in (select top 10 [Col1] from #take order by [Col2] desc) then 0
        else 2
        end, [Col2] desc

答案 1 :(得分:0)

具有以下表格结构

CREATE TABLE final
    ([col1] varchar(10), [col2] int)
;

INSERT INTO final
    ([col1], [col2])
VALUES
    ('App', 86748),
    ('AppService', 832),
    ('BK', 21227),
    ('Cap', 160272),
    ('Fukusima', 1634),
    ('McBaa', 1727),
    ('Others', 6718)
;

以下查询将给出确切的结果

select * from final
        order by 
        case when [Col1] in (select top 6 [Col1] from final order by [Col1] asc) then Col2 
        end desc, 
        [Col1] asc


col1       |    col2
-----------------------
Cap        |    160272
App        |    86748
BK         |    21227
McBaa      |    1727
Fukusima   |    1634
AppService |    832
Others     |    6718