SQL Server OFFSET和LIMIT

时间:2016-02-03 16:14:52

标签: sql sql-server

我正在尝试设置偏移和限制,我尝试了以下内容:

public class Product {

    private Integer id;
    private Integer companyId;
    private Integer categoryId;
    private String title;
    private String price;
    private boolean isExpanded = false;
    public Product(){

    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public boolean isExpanded() {
        return isExpanded;
    }

    public void setIsExpanded(boolean isExpanded) {
        this.isExpanded = isExpanded;
    }
}

但是我收到了这个错误:

  

列名称'rownumber'无效。

请帮忙。

4 个答案:

答案 0 :(得分:4)

您应该在查询中添加另一个步骤。 ROW_NUMBER()无法在您定义它的同一查询中使用,因此您必须将其全部包装在另一个选择中,如下所示。 where子句与FROM表/查询中的所有字段相关,因此rownumber尚不存在。

select * from
(SELECT Job_No,
        ROW_NUMBER() OVER(ORDER BY Job_No) AS rownumber,
        BaselineStart, BaselineFinish, ExpectedStart, ExpectedFinish,
        ScheduledStart, ScheduledFinish, ActualStart, ActualFinish
        FROM Schedule)
WHERE rownumber BETWEEN 10 AND 20

答案 1 :(得分:2)

使用CTE

WITH Result AS 
(
SELECT Job_No, 
   ROW_NUMBER() OVER(ORDER BY Job_No) AS rownumber, 
   BaselineStart, 
   BaselineFinish, 
   ExpectedStart, 
   ExpectedFinish, 
   ScheduledStart, 
   ScheduledFinish, 
   ActualStart, 
   ActualFinish 
FROM Schedule
)
SELECT  *
FROM    Result
WHERE   rownumber BETWEEN 10 AND 20

答案 2 :(得分:2)

在SQL 2012+中,您可以在ORDER BY子句中使用新的OFFSET and FETCH NEXT参数:

SELECT Columns
FROM MyTable
ORDER BY SomeColumn
OFFSET 10 ROWS --this means start with row 11
FETCH NEXT 10 ROWS ONLY  --this means limit the results to the next 10 rows.

因此,上述查询将返回按SomeColumn

排序的第11 - 20行

答案 3 :(得分:1)

从SQLServer 2012开始,由于未指定版本

下面是使用offset和fetch的版本,下面的代码将忽略前10行并获得jobno排序的下10行

SELECT Job_No, 
      BaselineStart, 
   BaselineFinish, 
   ExpectedStart, 
   ExpectedFinish, 
   ScheduledStart, 
   ScheduledFinish, 
   ActualStart, 
   ActualFinish 
FROM Schedule
order by job_no
offset  10 rows fetch next 10 rows only;