在SQL中检索第二个10个UNIQUE行

时间:2015-02-12 10:41:18

标签: sql sql-server distinct between rownum

我想在我的sql数据库中检索第二个10个UNIQUE行,为了选择第二个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行。 ..如何从RowNum中排除DISTINCT

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

3 个答案:

答案 0 :(得分:1)

您需要使用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

答案 1 :(得分:0)

如果你想在结果中区分这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,则可以使用新的甜蜜语句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

答案 2 :(得分:0)

SELECT DISTINCT col1, col2 
FROM MyTable
ORDER BY ID
LIMIT 10, 19