Programming

SQL Server에 대한 LIMIT 및 OFFSET에 해당합니까?

procodes 2020. 6. 4. 21:05
반응형

SQL Server에 대한 LIMIT 및 OFFSET에 해당합니까?


PostgreSQL에는 결과 세트를 매우 쉽게 페이지 매김 할 수 있는 LimitOffset키워드가 있습니다.

Sql Server에 해당하는 구문은 무엇입니까?


LIMITis 와 동일 SET ROWCOUNT하지만 일반 페이지 매김을 원하면 다음과 같은 쿼리를 작성하는 것이 좋습니다.

;WITH Results_CTE AS
(
    SELECT
        Col1, Col2, ...,
        ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
    FROM Table
    WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit

페이징 옵션을 변경하거나 사용자가 변경하도록 허용 한 경우 오프셋 및 제한의 매개 변수화가 장점입니다.

참고 :@Offset 매개 변수는 정상 제로 인덱스보다이 아니라 하나 기반의 인덱싱을 사용해야합니다.


이 기능은 이제 SQL Server 2012에서 쉽게 사용할 수 있습니다.이 기능은 SQL Server 2012부터 작동합니다.

SQL Server에서 11 ~ 20 행을 선택하도록 오프셋으로 제한 :

SELECT email FROM emailTable 
WHERE user_id=3
ORDER BY Id
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;
  • OFFSET: 건너 뛴 행 수
  • NEXT: 필요한 다음 행 수

참조 : https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-2017


select top {LIMIT HERE} * from (
      select *, ROW_NUMBER() over (order by {ORDER FIELD}) as r_n_n 
      from {YOUR TABLES} where {OTHER OPTIONAL FILTERS}
) xx where r_n_n >={OFFSET HERE}

참고 : 이 솔루션 ROW_NUMBER()은 구현 되었을 때부터 SQL Server 2005 이상에서만 작동 합니다.


공통 테이블 표현식에서 ROW_NUMBER를 사용하여이를 달성 할 수 있습니다.

;WITH My_CTE AS
(
     SELECT
          col1,
          col2,
          ROW_NUMBER() OVER(ORDER BY col1) AS row_number
     FROM
          My_Table
     WHERE
          <<<whatever>>>
)
SELECT
     col1,
     col2
FROM
     My_CTE
WHERE
     row_number BETWEEN @start_row AND @end_row

나를 위해 OFFSET과 FETCH를 함께 사용하는 것이 느렸으므로 TOP과 OFFSET의 조합을 다음과 같이 사용했습니다 (더 빠름).

SELECT TOP 20 * FROM (SELECT columname1, columname2 FROM tablename
    WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS) aliasname

참고 : TOP과 OFFSET을 같은 쿼리에서 함께 사용하는 경우 :

SELECT TOP 20 columname1, columname2 FROM tablename
    WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS

그런 다음 오류가 발생하므로 TOP과 OFFSET을 함께 사용하려면 하위 쿼리로 구분해야합니다.

SELECT DISTINCT를 사용해야하는 경우 쿼리는 다음과 같습니다.

SELECT TOP 20 FROM (SELECT DISTINCT columname1, columname2
    WHERE <conditions...> ORDER BY columname1 OFFSET 100 ROWS) aliasname

참고 : DISTINCT와 함께 SELECT ROW_NUMBER를 사용하면 효과가 없었습니다.


다른 샘플 :

declare @limit int 
declare @offset int 
set @offset = 2;
set @limit = 20;
declare @count int
declare @idxini int 
declare @idxfim int 
select @idxfim = @offset * @limit
select @idxini = @idxfim - (@limit-1);
WITH paging AS
    (
        SELECT 
             ROW_NUMBER() OVER (order by object_id) AS rowid, *
        FROM 
            sys.objects 
    )
select *
    from 
        (select COUNT(1) as rowqtd from paging) qtd, 
            paging 
    where 
        rowid between @idxini and @idxfim
    order by 
        rowid;

There is here someone telling about this feature in sql 2011, its sad they choose a little different keyword "OFFSET / FETCH" but its not standart then ok.


Adding a slight variation on Aaronaught's solution, I typically parametrize page number (@PageNum) and page size (@PageSize). This way each page click event just sends in the requested page number along with a configurable page size:

begin
    with My_CTE  as
    (
         SELECT col1,
              ROW_NUMBER() OVER(ORDER BY col1) AS row_number
     FROM
          My_Table
     WHERE
          <<<whatever>>>
    )
    select * from My_CTE
            WHERE RowNum BETWEEN (@PageNum - 1) * (@PageSize + 1) 
                              AND @PageNum * @PageSize

end

The closest I could make is

select * FROM( SELECT *, ROW_NUMBER() over (ORDER BY ID ) as ct from [db].[dbo].[table] ) sub where ct > fromNumber  and ct <= toNumber

Which I guess similar to select * from [db].[dbo].[table] LIMIT 0, 10


select top (@TakeCount) * --FETCH NEXT
from(
    Select  ROW_NUMBER() OVER (order by StartDate) AS rowid,*
    From YourTable
)A
where Rowid>@SkipCount --OFFSET

@nombre_row :nombre ligne par page  
@page:numero de la page

//--------------code sql---------------

declare  @page int,@nombre_row int;
    set @page='2';
    set @nombre_row=5;
    SELECT  *
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY etudiant_ID ) AS RowNum, *
      FROM      etudiant

    ) AS RowConstrainedResult
WHERE   RowNum >= ((@page-1)*@nombre_row)+1
    AND RowNum < ((@page)*@nombre_row)+1
ORDER BY RowNum

Since nobody provided this code yet:

SELECT TOP @limit f1, f2, f3...
FROM t1
WHERE c1 = v1, c2 > v2...
AND
    t1.id NOT IN
        (SELECT TOP @offset id
         FROM t1
         WHERE c1 = v1, c2 > v2...
         ORDER BY o1, o2...)
ORDER BY o1, o2...

Important points:

  • ORDER BY must be identical
  • @limit can be replaced with number of results to retrieve,
  • @offset is number of results to skip
  • Please compare performance with previous solutions as they may be more efficient
  • this solution duplicates where and order by clauses, and will provide incorrect results if they are out of sync
  • on the other hand order by is there explicitly if that's what's needed

-- @RowsPerPage  can be a fixed number and @PageNumber number can be passed 
DECLARE @RowsPerPage INT = 10, @PageNumber INT = 2

SELECT *

FROM MemberEmployeeData

ORDER BY EmployeeNumber

OFFSET @PageNumber*@RowsPerPage ROWS

FETCH NEXT 10 ROWS ONLY

In SQL server you would use TOP together with ROW_NUMBER()

참고URL : https://stackoverflow.com/questions/2135418/equivalent-of-limit-and-offset-for-sql-server

반응형