如何在sql server 2016中对奇数序列的记录进行排序

时间:2018-03-05 15:07:52

标签: sql-server sql-server-2016

如何从列表底部的记录集中制作单个记录。

0. Select All
1. Apple
2. Banana
3. Mango

我需要放置"全选"在底部:

1. Apple
2. Banana
3. Mango
0. Select All

基于Id,而非价值。

3 个答案:

答案 0 :(得分:3)

您应该将计算出的排序字段与主表的-ALL-值合并,然后按计算字段对结果进行排序。

SELECT
    *
FROM
(
    SELECT
       RowOrder=2,
       RowValue='-ALL-'
    UNION
    SELECT
       RowOrder=1,
       RowValue=FruitTable.Value
    FROM
       FruitTable
)AS X
ORDER BY
   X.RowOrder,
   x.RowValue

答案 1 :(得分:2)

请尝试这样。

SELECT [Values] from 
(
    SELECT 'Select All' [Values] UNION ALL
    SELECT 'Apple' UNION ALL
    SELECT 'Banana' UNION ALL
    SELECT 'Mango' 
)u
ORDER BY Case [Values] WHEN 'SELECT All' THEN 1 ELSE 0 END,[Values]

答案 2 :(得分:2)

与其他答案类似,但我假设你理解方法:

    ;WITH T (List, Sort) AS 
    (
    SELECT 'Apple' , 1
    UNION ALL
    SELECT 'Banana' ,1 
    UNION ALL 
    SELECT 'Mango' ,1 
    ),
    T2 (List , Sort) AS 
    (
    SELECT * 
    FROM T
    UNION ALL
    SELECT 'Select All'  , 2
    )
    SELECT List 
    FROM T2
    ORDER BY Sort