1

有人可以帮忙解决这个问题吗?我一直在愚弄 LIMIT 或 TOP,但我认为我偏离了轨道。我想从表中返回所有字段,但在新表中最多有 3 个重复的 id。

桌子

id    first    last    
===================
1    John    Doe    
1    John    Doe   
1    John    Doe   
1    John    Doe   
2    Mary    Green  
2    Mary    Green  
3    Stacy   Kirk  
3    Stacy   Kirk  
3    Stacy   Kirk  
3    Stacy   Kirk  
3    Stacy   Kirk  

期望的结果(最多 3 个 ID)

id    first    last  
====================
1    John     Doe  
1    John     Doe  
1    John     Doe  
2    Mary     Green  
2    Mary     Green  
3    Stacy    Kirk  
3    Stacy    Kirk  
3    Stacy    Kirk  

谢谢!

4

1 回答 1

3

既然你提到TOP了,这是为了SQL SERVER

SELECT id, first, last
FROM
  (
  SELECT id, first, last,
        ROW_NUMBER() OVER (PARTITION BY ID ORDER BY LAST) rn
  FROM TABLE1
  ) s
WHERE s.rn <= 3
于 2012-11-16T14:13:16.297 回答