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

问题描述 投票:0回答:3

如何从列表底部的记录集中创建单个记录。

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

我需要在底部放置“全选”:

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

基于Id,而不是价值。

sql-server sql-server-2016
3个回答
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

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

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]
© www.soinside.com 2019 - 2024. All rights reserved.