Sql-server – Combine the same column from multiple rows into one row

join;sql server

I am joining two tables HR and UserDefined based on the Employee_ID:

HR Table

First Name  Last Name   Employee_ID
----------  ---------   -----------
Joe         Smith       456654

User Defined Table

Area    ud_1_text   ud_2_text   Employee_ID
----    ---------   ----------  -----------
1       ABCD1234    31/08/2018  456654
2       69090       23/05/2022  456654

Now I know that if Area equals 1 then it is a "Drivers Licence" and if Area equals 2 that it is a "First Aid Certification".

I would like to be able to return the following in one line per Employee_ID:

Employee_ID First Name  Last name   D/L Number  Expiry      First Aid Expiry
----------- ----------  ---------   ----------  ----------  --------- ----------
456654      Joe         Smith       ABCD1234    31/08/2018  69090     23/05/2022

Any ideas on how to do this?
Microsoft SQL Server query please.

Best Answer

Join to User Defined Table twice, once with Area = 1 and once with Area = 2.

from [HR Table] as HT
  inner join [User Defined Table] as UT1
    on HT.Employee_ID = UT1.Employee_ID and
       UT1.Area = 1
  inner join [User Defined Table] as UT2
    on HT.Employee_ID = UT2.Employee_ID and
       UT2.Area = 2

Get the D/L Number with Expiry from UT1 and First Aid with Expiry from UT2