SQL数据库查询为一个值选择不同的对应值

时间:2015-05-05 19:06:27

标签: sql sql-server

如何从表中获得这样的输出? 如果我有一个表格,例如如下所示

First Name         Last Name
----------    

 1. John            Doe
 2. John           Ruggles
 3. Ricky          Rog
 4. kelly          Ali
 5. Ricky           Gyri

我想在下面显示

First Name       Last Name

 1.John           Doe
                  Ruggles

 2. Kelly         Ali

 3. Ricky         Rog
                  Gyri

与每个名字一样,我想显示姓氏。我希望First Name只出现一次。请帮我。它的表格数据,名字和姓氏是不同的列

1 个答案:

答案 0 :(得分:2)

您可以使用row_number() analytic function来确定姓氏是否已更改:

select  case
        when row_number() over (partition by FirstName 
                                order by FirstName, LastName) = 1 
            then FirstName
        else ''
        end as FirstName
,       LastName
from    YourTable
order by
        YourTable.FirstName
,       LastName

Example at SQL Fiddle.