Hello, I would do as follows there are many others but please verify whether the expected results.
Create TAble #Old_Table
(Id int, National_Code varchar(20))
Create TAble #New_Table
(Id int, National_Code varchar(20))
Insert into #Old_Table
Values (1,'0000000000')
,(2, '1111111111')
,(3, '1111111111')
,(4, '1111111111')
,(5, '1111111111')
,(6, '2222222222')
,(7, '3333333333')
,(8, '2222222222')
,(9, '2222222222')
,(10, '2222222222')
SELECT Id, National_Code
,RANK() OVER
(PARTITION BY National_Code ORDER BY Id DESC) AS nTimes
INTO #Temporal
FROM #Old_Table
ORDER BY National_Code;
INSERT INTO #New_Table(Id, National_Code )
select Id, National_Code from #Temporal
where nTimes <= 3
SELECT * FROM #New_Table
DROP TABLE #Temporal
DROP TABLE #New_Table
DROP TABLE #Old_Table
Results:
Id National_Code
----------- --------------------
1 0000000000
5 1111111111
4 1111111111
3 1111111111
10 2222222222
9 2222222222
8 2222222222
7 3333333333
You're welcome...
Ing. Aneurys Tapia González
DBA + BI Architect
Dominican Republic
atapia@outlook.com | admin@atapia.net
http://sqlservermasbi.wordpress.com
http://atapia.net