重复时SQL SELECT上的自动递增值

时间:2013-07-05 19:07:19

标签: sql sql-server select

我想知道是否有可能做到以下几点。我有一个名字和姓氏的数据库,我想查询它以便结果是firstname.lastname,或者在firstname.lastname已被返回的情况下,它应该是firstname.lastname1(如果firstname.lastname1则为2)已经退回,等)。所以查询下表:

| ID | Firstname | Lastname |
|  1 |      John |    Smith |
|  2 |      John |    Smith |
|  3 |      Jane |      Doe |

将返回

John.Smith
John.Smith1
Jane.Doe

MSSQL Server 2008上存在数据库。 任何帮助,将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:2)

SELECT
    FirstName + '.' + LastName
        + IsNull(cast(NullIf(ROW_NUMBER() OVER(PARTITION BY FirstName + '.'  + LastName ORDER BY ID) - 1, 0) as varchar(10)), '')
FROM
    TableName

答案 1 :(得分:1)

喜欢这个

SELECT FirstName + '.' + LastName +
    CAST(ROW_NUMBER() OVER(PARTITION BY FirstName, LastName ORDER BY ID) As Varchar(9))
FROM YourTable

答案 2 :(得分:0)

这应该这样做

SELECT
CASE WHEN Seq = 1 THEN Firstname + '.' + Lastname 
     ELSE Firstname + '.' + Lastname + CAST(ID AS VARCHAR)
END As Name
FROM (
  SELECT ID, Firstname, Lastname,
  ROW_NUMBER() OVER (PARTITION BY Firstname, Lastname ORDER BY ID) As Seq
  FROM Sometable
) tbl