SQL通过OFFSET / FETCH获取每个类别的产品

时间:2018-10-25 15:49:57

标签: sql sql-server-2012

我有这个查询来打印每个类别的10种产品

WITH MyRowSet AS (SELECT *, 
        ROW_NUMBER() OVER (PARTITION BY p.cateID ORDER BY p.cateID DESC) 
        AS RowNum 
        FROM Product p )  
SELECT TOP 100 * FROM MyRowSet WHERE RowNum <= 10

然后我想用OFFSET / FETCH获得下100个产品。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要使用order by子句来指定要提取的行和要偏移的行:

WITH MyRowSet AS (SELECT *, 
        ROW_NUMBER() OVER (PARTITION BY p.cateID ORDER BY p.cateID DESC) 
        AS RowNum 
        FROM Product p )  
SELECT * 
FROM MyRowSet 
WHERE RowNum <= 10
ORDER BY p.cateId, rownum
OFFSET 100 ROWS FETCH NEXT 100 ROWS ONLY;