限制sql查询中返回的记录数

时间:2011-04-20 13:40:54

标签: sql

如果“select * from table;”给出下面的结果, 如何限制它只显示每个参考的前3个记录?

感谢

ref other field
----------------------
1234 a
1234 b
1234 c
1234 d
1234 e
5678 a
5678 b
5678 c
5678 d 

3 个答案:

答案 0 :(得分:2)

对于Microsoft SQL Server 2005 +:

SELECT ref, OtherField
    FROM (SELECT ref, OtherField, 
                 ROW_NUMBER() OVER(PARTITION BY ref ORDER BY OtherField) AS RowNum
              FROM YourTable) t
    WHERE t.RowNum <= 3

相同的查询,使用CTE

WITH cteRowNum AS (
    SELECT ref, OtherField, 
           ROW_NUMBER() OVER(PARTITION BY ref ORDER BY OtherField) AS RowNum
        FROM YourTable
)
SELECT ref, OtherField
    FROM cteRowNum
    WHERE RowNum <= 3

答案 1 :(得分:1)

使用Oracle:

WITH subquery as 
(
  SELECT ref, row_number() over (partition by ref) rank, other_field
    FROM my_table
)
SELECT ref, other_field from subquery where rank <= 3;

查找Oracle analytic functions

答案 2 :(得分:0)

另一种可在SQL Server 2005 +

中使用的解决方案
Select ...
From MyTable As T
    Cross Apply (
                Select TOP 3 T2.OtherField
                From MyTable As T2
                Where T2.ref = T.ref
                Order By T2.OtherField
                ) As Z