SQL查询返回表中的所有列,但最多有3个重复的id

时间:2012-11-16 14:09:39

标签: sql sql-server tsql

有人可以帮忙解决这个问题吗?我一直在玩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  

谢谢!

1 个答案:

答案 0 :(得分: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