查询将数字附加到记录中它发现重复

时间:2014-06-06 22:28:49

标签: sql append

我有一个包含以下字段的SQL表:Letter,Number,Result

Title   Name    Result  
Mr      Mark    
Mr      Mark    
Mr      Luke    
Mr      John
Mr      John

我需要创建一个更新查询以将结果显示为

Title   Name    Result
Mr      Mark    MrMark
Mr      Mark    MrMark2
Mr      Luke    MrLuke
Mr      John    MrJohn
Mr      John    MrJohn2

请注意,第二条和第五条记录的附加数字为2,因为它之前已找到相同的记录(相同的标题和名称)。

请帮忙。

2 个答案:

答案 0 :(得分:0)

如果是MS SQL,请尝试使用ROW_NUMBER和PARTITION BY?

DECLARE @temp TABLE (Title NVARCHAR(200), Name NVARCHAR(200), Result NVARCHAR(200));

INSERT @temp
    SELECT 'Mr', 'Mark', NULL
    UNION ALL
    SELECT 'Mr', 'Mark', NULL
    UNION ALL
    SELECT 'Mr', 'Luke', NULL
    UNION ALL
    SELECT 'Mr', 'John', NULL
    UNION ALL
    SELECT 'Mr', 'John', NULL

SELECT * FROM @temp

DECLARE @tempWithOrdering TABLE (RowNum INT, Title NVARCHAR(200), Name NVARCHAR(200), Result NVARCHAR(200));

INSERT @tempWithOrdering
    SELECT ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Title ), Title, Name, Result FROM @temp 

SELECT * FROM @tempWithOrdering 

SELECT 
    Title,
    Name,
    Result = (
        SELECT TOP(1) Name + 
            CASE RowNum
                WHEN t1.RowNum THEN ''
                ELSE CAST(t1.RowNum AS NVARCHAR(12))
            END
        FROM @tempWithOrdering 
        WHERE Name = t1.Name
    )
FROM @tempWithOrdering t1

答案 1 :(得分:0)

假设您正在使用sql server并且副本位于字段' Name' 。试试这个。 使用Analytic fn ROW_NUMBER();

如果是Oracle,请使用 || 而不是 +

WITH TEMP AS
(
SELECT Title ,  Name,
ROW_NUMBER() OVER (PARTITION BY Name ORDER BY bill_period) AS RK
FROM TABLE1
)
SELECT Title ,  Name,Title + Name +RK FROM TEMP;