按列中的特定值排序,而不使用case语句

时间:2011-08-04 11:38:32

标签: sql sql-server tsql sql-order-by

我想以下列格式获取记录:

如果我有像

这样的记录
A, B, C, D 

我希望按此顺序获得记录 -

B, A, C, D, E, F, G, H, so on,

但我需要值B应该在第一行...

3 个答案:

答案 0 :(得分:4)

试试这个:

SELECT
    *, 1 AS SortBy 
    FROM YourTable
    WHERE YourCol='B'
UNION ALL
SELECT
    *, 2 AS SortBy 
    FROM YourTable
    WHERE YourCol!='B'
    ORDER BY SortBy, YourCol

您没有任何理由不想使用CASE。我还是试一试,看看哪个更快,UNION ALLCASE方法:

SELECT
    *
    FROM YourTable
    ORDER BY CASE WHEN YourCol='B' then 1 ELSE 2 END, YourCol

编辑工作示例:

DECLARE @YourTable table (YourCol char(1), RowValue varchar(5))
INSERT @YourTable VALUES ('A','aaa')
INSERT @YourTable VALUES ('A','aa')
INSERT @YourTable VALUES ('B','bbb')
INSERT @YourTable VALUES ('B','bb')
INSERT @YourTable VALUES ('C','ccc')
INSERT @YourTable VALUES ('D','ddd')
INSERT @YourTable VALUES ('E','eee')
INSERT @YourTable VALUES ('F','fff')

SELECT
    *, 1 AS SortBy 
    FROM @YourTable
    WHERE YourCol='B'
UNION ALL
SELECT
    *, 2 AS SortBy 
    FROM @YourTable
    WHERE YourCol!='B'
    ORDER BY SortBy, YourCol

输出:

YourCol RowValue SortBy
------- -------- -----------
B       bbb      1
B       bb       1
A       aaa      2
A       aa       2
C       ccc      2
D       ddd      2
E       eee      2
F       fff      2

(8 row(s) affected)

答案 1 :(得分:0)

SELECT * from mytable where mycolumn = "B";

接着是

SELECT * from mytable where mycolumn != "B" order by mycolumn asc;

答案 2 :(得分:0)

声明并填充表格:

DECLARE @t TABLE (col1 CHAR)
INSERT @t
SELECT char(number+ 65)
FROM master..spt_values
WHERE type = 'P' AND number < 6 

查询1:

SELECT *, cast(ascii(col1)-66 as bit) * 2 + ascii(col1) [orderby]
FROM @t 
ORDER BY cast(ascii(col1)-66 as bit) * 2 + ascii(col1) 

QUERY2:

SELECT *
FROM @t 
ORDER BY replace(col1, 'B', ' ') 

Query1的结果:( [orderby]列仅包含在文档中)

col1 orderby
---- --------
B    66
A    67
C    69
D    70
E    71
F    72