-3
sno Fname   Sname
1   Vandana Pandey
2   Ritesh  Kumar
3   Kumar   Ritesh
4   Pandey  Vandana
5   Priya   Kapoor

假设我有一个表格,其中插入了这些值。现在我想生成行号。相同名称的行号应相同,输出应为:-

sno Fname   Sname   RowNumber
1   Vandana Pandey  1
2   Ritesh  Kumar   2
3   Kumar   Ritesh  2
4   Pandey  Vandana 1
5   Priya   Kapoor  3

因为 Vandana Pandey 的名字在 sno-1 和 4 中是相同的。

请帮帮我。

4

1 回答 1

1
    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
于 2013-04-14T15:54:13.040 回答