Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Database Query selecting different corresponding values for one value

Tags:

sql

sql-server

How can I get the output like this from the table? If I have a table for example shown below

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

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

I want to show this as below

First Name       Last Name

 1.John           Doe
                  Ruggles

 2. Kelly         Ali

 3. Ricky         Rog
                  Gyri

Like for each name I want to display last name. I want First Name will appear only one time. Please help me. Its a tabular data, first name and last name are different columns

like image 752
Rebecca Avatar asked May 03 '26 15:05

Rebecca


1 Answers

You can use the row_number() analytic function to determine if the last name has changed:

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.

like image 99
Andomar Avatar answered May 05 '26 07:05

Andomar