如何更改sql行顺序

时间:2018-04-17 10:42:45

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

我有一个表,每行包含1到10列。 如果我想从从8开始的表中进行选择,那么如何根据样本输出更改顺序。

Sample output:
8
9
10
1
2
3
4
5
6
7

3 个答案:

答案 0 :(得分:7)

您可以在order by中使用表达式。一种方法是:

order by (case when col >= 8 then 1 else 2 end),
         col asc

答案 1 :(得分:1)

针对您的情况:

SELECT Col1 
FROM Your_Table
ORDER BY (CASE WHEN col1 < 8 THEN col1+10 ELSE col1 END)

<强>查询:

DECLARE @T TABLE(col1 INT)
INSERT INTO @T VALUES(1)
INSERT INTO @T VALUES(2)
INSERT INTO @T VALUES(3)
INSERT INTO @T VALUES(4)
INSERT INTO @T VALUES(5)
INSERT INTO @T VALUES(6)
INSERT INTO @T VALUES(7)
INSERT INTO @T VALUES(8)
INSERT INTO @T VALUES(9)
INSERT INTO @T VALUES(10)

SELECT Col1 
FROM @T
ORDER BY (CASE WHEN col1 < 8 THEN col1+10 ELSE col1 END)

<强>输出:

Col1
8
9
10
1
2
3
4
5
6
7

答案 2 :(得分:0)

尝试以下方案以获取起始值的动态输入。如果你想从6开始,那么你的初始值为8,那么下面的逻辑就可以了。

DECLARE @tempTable TABLE(myColumn INT)
INSERT INTO @tempTable VALUES(1)
INSERT INTO @tempTable VALUES(2)
INSERT INTO @tempTable VALUES(3)
INSERT INTO @tempTable VALUES(4)
INSERT INTO @tempTable VALUES(5)
INSERT INTO @tempTable VALUES(6)
INSERT INTO @tempTable VALUES(7)
INSERT INTO @tempTable VALUES(8)
INSERT INTO @tempTable VALUES(9)
INSERT INTO @tempTable VALUES(10)
INSERT INTO @tempTable VALUES(11)
INSERT INTO @tempTable VALUES(12)
INSERT INTO @tempTable VALUES(13)
INSERT INTO @tempTable VALUES(14)
INSERT INTO @tempTable VALUES(15)
INSERT INTO @tempTable VALUES(16)

Declare @startValue Int = 12  --"YOUR_VALUE" [Ex: 8]
SELECT myColumn 
FROM @tempTable
ORDER BY (CASE WHEN myColumn < @startValue THEN myColumn+(select count(*) from @tempTable) ELSE myColumn END)

让我知道逻辑对你有用吗?谢谢,