1

我想知道是否可以执行以下操作。我有一个名字和姓氏的数据库,我想查询它,以便结果是 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 上。任何帮助将不胜感激。谢谢!

4

3 回答 3

2
SELECT
    FirstName + '.' + LastName
        + IsNull(cast(NullIf(ROW_NUMBER() OVER(PARTITION BY FirstName + '.'  + LastName ORDER BY ID) - 1, 0) as varchar(10)), '')
FROM
    TableName
于 2013-07-05T19:25:53.133 回答
1

像这样

SELECT FirstName + '.' + LastName +
    CAST(ROW_NUMBER() OVER(PARTITION BY FirstName, LastName ORDER BY ID) As Varchar(9))
FROM YourTable
于 2013-07-05T19:14:02.547 回答
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
于 2013-07-05T19:15:52.123 回答