Skip to content
Advertisement

Sql data in multiple rows – get output in one row

I have a table in sql which looks like below. Basically typeid column determines which type of data it is like address, name, department etc. So, there are multiple rows in the table for one employee.

table

ID employee Type id column 1 column 2 column 3
1 1 5 building 6 null New York
2 1 6 Adam Smith
3 1 7 null null Finance
4 1 8 null AS7836 null

is it possible to write a query to get an output for one employee in one row – like below ? Thanks.

output

Emplyee first name Last name department payroll nu Address City
1 Adam Smith Finance AS7836 building 6 New York

Advertisement

Answer

Here is an example of self joins to get your results:

select t.Employee
    , t.column1 first_name
    , t.column2 last_name
    , t2.column3 department
    , t3.column2 payroll_nu
    , t4.column1 address
    , t4.column3 city
from tbl t
inner join tbl t2
    on t.employee = t2.employee
    and t2.TypeID = 7
inner join tbl t3
    on t.employee = t2.employee
    and t3.TypeID = 8
inner join tbl t4
    on t.employee = t4.employee
    and t4.TypeID = 5
where t.employee = 1
    and t.TypeID = 6

Example Results:

Example Results

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement