USE tempdb;
GO
IF OBJECT_ID('dbo.name','U') IS NOT NULL DROP TABLE dbo.name;
CREATE TABLE dbo.name
(
sno INT NOT NULL PRIMARY KEY
,fname VARCHAR(50)
,lname VARCHAR(50)
)
INSERT INTO dbo.name(sno,fname,lname)
VALUES
(1,'Vandana','Pandey')
,(2,'Ritesh','Kumar')
,(3,'Kumar','Ritesh')
,(4,'Pandey','Vandana')
,(5,'Priya','Kapoor');
WITH cte_names AS
(
Select n.sno
,n.fname + ' ' + n.lname AS fname_first
From dbo.name n
UNION ALL
Select n.sno
,n.lname + ' ' + n.fname AS lnames_first
From dbo.name n
)
,cte_dense_rank AS
(
Select cn.sno
,cn.fname_first
,DENSE_RANK() OVER( ORDER BY cn.sno) AS [Row_Number]
From cte_names cn
)
, cte_row_num AS
(
Select n.sno,rn.[Row_Number]
From dbo.name n
Inner Join cte_dense_rank AS rn
ON n.fname + ' ' + n.lname = rn.fname_first
)
Select n.sno,n.fname,n.lname
,DENSE_RANK() OVER(ORDER BY MIN(mr.[Row_Number])) AS [Row_Number]
From dbo.name n
Inner Join cte_row_num mr
ON n.sno = mr.sno
Group By n.sno,n.fname,n.lname
Order BY n.sno