在Sql Server中不使用order by选择行作为第一行

时间:2013-09-12 06:57:05

标签: sql sql-server

示例:

id  name  agreement
32  fahid   52
43  nahid   51
31  zal     52

想要通过协议进行选择,但我希望保留给定id的顶部,如果我使用order by则始终对id进行排序。 如果我使用agreement=52id=32搜索预期结果:

32 fahid 52
31 fahid 52

3 个答案:

答案 0 :(得分:1)

您可以按顺序使用多个字段 order by id,agreement

答案 1 :(得分:1)

试试这个

DECLARE @id INT
DECLARE @agreement INT

SET @id = 32
SET @agreement = 52

SELECT [id]
, (SELECT [name] FROM Table1 WHERE [id] = @id) AS [name]
, [agreement] FROM Table1 
WHERE [agreement] = @agreement

SQL FIDDLE DEMO

<强>输出

id  name    agreement
32  fahid   52
31  fahid   52

答案 2 :(得分:0)

在mysql中使用LIMIT

MySQL语法

SELECT column_name(s)FROM table_name WHERE (condition) LIMIT number;

实施例

SELECT * FROM Persons WHERE agreement=52 LIMIT 5;

Oracle语法

SELECT column_name(s)FROM table_name WHERE ROWNUM <= number; 

实施例

SELECT * FROM Persons WHERE ROWNUM <=5;