create table table2( ConID int, CertID int, CertDate datetime)insert into table2 values(1,1, '1/1/2001')insert into table2 values(1,2, '2/3/2008')insert into table2 values(1,3, '1/1/2012')insert into table2 values(2,2, '2/2/2012')
select conid,location,[cert1date],[cert2date],[cert3date],[cert4date]from (select #table1.conid, location, certdesc+'date' certname,certdate from #table1 cross join #table3 left outer join #table2 on #table1.conid=#table2.conid and #table3.certdesc=#table2.[cert] where exists (select null from #table2 where conid=#table1.conid) ) p pivot (max(certdate) for certname in ([cert1date],[cert2date],[cert3date],[cert4date])) pvtorder by conID
select t1.conid, t1.location, t3.certdesc + 'date' as certname, t2.certdatefrom table1 t1 cross join table3 t3 left outer join table2 t2 on t2.cert = t3.certdesc and t1.conid = t2.conid
SELECT location, MAX( CASE WHEN cert = 'cert1' THEN certdate END) AS cert1, MAX( CASE WHEN cert = 'cert2' THEN certdate END) AS cert2, MAX( CASE WHEN cert = 'cert3' THEN certdate END) AS cert3, MAX( CASE WHEN cert = 'cert4' THEN certdate END) AS cert4FROM #table1 t1JOIN #table2 t2 ON t1.conid = t2.conidGROUP BY t1.location