@manhng

Welcome to my blog!

RANK + DENSE_RANK + ROW_NUMBER + OFFSET + FETCH

June 29, 2020 13:36

T-SQL: RANK (edit)

https://stackoverflow.com/questions/11013575/sql-partial-group-by

https://sqlperformance.com/2015/01/t-sql-queries/pagination-with-offset-fetch

https://stackoverflow.com/questions/51173376/ms-sql-server-paging

https://www.sqlshack.com/introduction-pagination-sql-server/

https://stackoverflow.com/questions/109232/what-is-the-best-way-to-paginate-results-in-sql-server

https://database.guide/pagination-in-sql-server-using-offset-fetch/

https://codingsight.com/implementing-paging-using-offset-fetch-next-in-sql-server/

RANK

CREATE TABLE t (
col CHAR
);

INSERT INTO t(col)
VALUES('A'),('B'),('B'),('C'),('D'),('D'),('E');

SELECT
col,
RANK() OVER (
ORDER BY col
) my_rank,
DENSE_RANK() OVER (
ORDER BY col
) my_dense_rank
FROM
t;

;WITH cte AS
(
SELECT col,
ROW_NUMBER() OVER (PARTITION BY col ORDER BY col DESC) AS MyRow
FROM t
)

SELECT col FROM cte WHERE MyRow = 1

Paging

CREATE TABLE dbo.Product
(ID INT NOT NULL,
ProductName NVARCHAR(50) NOT NULL,
ProductPrice DECIMAL(18,2),
)

INSERT INTO Product
SELECT
1,
N'Apple',
100
UNION ALL
SELECT
2,
N'Google',
200
UNION ALL
SELECT
3,
N'Microsoft',
300
UNION ALL
SELECT
4,
N'SamSung',
100
GO
SELECT (list-of-columns)
FROM YourTable
(optionally add JOINs here)
WHERE (conditions)
ORDER BY (some column)
      OFFSET n ROWS
      FETCH NEXT y ROWS ONLY

Categories

Recent posts