在 SQL 中检索第二个 10 个唯一行

retrieve second 10 UNIQUE rows in SQL

我想在我的 sql 数据库中检索第二个 10 个唯一行,为了选择第二个 10 行,我使用下一个脚本:

SELECT col1, col2 FROM (
    SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
    FROM MyTable
) AS MyDerivedTable WHERE MyDerivedTable.RowNum BETWEEN 10 AND 19

但现在我想要该集合中的 UNIQUE 行,当我在下一个示例中使用 DISTINCT 时,DISTINCT 也会超过 RowNum,这使得每一行都是 DISTINCT行...如何从我的 DISTINCT 中排除 RowNum

SELECT col1, col2 FROM (
    SELECT DISTINCT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
    FROM MyTable
) AS MyDerivedTable WHERE MyDerivedTable.RowNum BETWEEN 10 AND 19

如果你想区分结果中的那 10 行,你可以在 Select 子句之外进行:

SELECT DISTINCT col1, col2 FROM (
    SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
    FROM MyTable
) AS MyDerivedTable WHERE MyDerivedTable.RowNum BETWEEN 10 AND 19

此外,如果您使用 SQL Server 2012,您可以使用新的 sweet 语句 OFFSET FETCH:

   SELECT DISTINCT col1, col2 FROM (
        SELECT col1, col2
        FROM MyTable
        ORDER BY ID
        OFFSET 10 ROWS FETCH FIRST 10 ROWS ONLY
    ) AS MyDerivedTable
SELECT DISTINCT col1, col2 
FROM MyTable
ORDER BY ID
LIMIT 10, 19

您需要使用 group by 而不是 distinct,因为它们应用于查询执行的不同时刻。当然,由于 col1col2ID 有 N:1 关系,您需要告诉 SQL 在对行编号时使用哪个 ID .这可能是 MAX(ID)。所以:

SELECT col1, col2 FROM (
    SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY MAX(ID)) AS RowNum
    FROM MyTable
    GROUP BY col1, col2
) AS MyDerivedTable WHERE MyDerivedTable.RowNum BETWEEN 10 AND 19