Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple column values as new rows SQL

I had a table that shows each employee and lists the positions that they have applied for as separate columns.

APPNO, Date_Applied, FirstName, LastName, Position1, Position2, Position3

I would like to return the multiple positions applied for as additional rows for the same employee. So if one person applied for 3 different positions it would return 3 different rows for that one employee.

APPNO, Date_Applied, FirstName, LastName, Position1,
APPNO, Date_Applied, FirstName, LastName, Position2
APPNO, Date_Applied, FirstName, LastName, Position3
like image 796
denny bono Avatar asked Nov 23 '25 03:11

denny bono


2 Answers

Normalization is really important, but something like this would work:

SELECT APPNO, Date_Applied, FirstName, LastName, Position1 AS position
UNION ALL
SELECT APPNO, Date_Applied, FirstName, LastName, Position2
WHERE Position2 IS NOT NULL
UNION ALL
SELECT APPNO, Date_Applied, FirstName, LastName, Position3
WHERE Position3 IS NOT NULL
like image 88
Kermit Avatar answered Nov 25 '25 17:11

Kermit


Another way using CROSS APPLY:

SELECT  t.APPNO,
        t.Date_Applied,
        t.FirstName,
        t.LastName,
        x.Position
FROM YourTable t
CROSS APPLY 
(
    VALUES
        (t.Position1),
        (t.Position2),
        (t.Position3)
) x (Position)
WHERE x.Position IS NOT NULL;
like image 36
Lamak Avatar answered Nov 25 '25 18:11

Lamak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!