从两个表中提取数据并提供所有数据元素

时间:2018-07-21 12:33:19

标签: sql sql-server tsql

我有一个用名称,SSN和日期创建的表。我想查看另一个表,仍然从我的第一个表中提取所有信息,但是如果在第二个表中找到了该名称,请提供该数据。如果不是,请提供一个Null值。我相信这是左联接,但可能会误会。

这是我的代码:

if object_id('tempdb..#ssns') is not null drop table #ssns 
create table #ssns
  (ssnId int, fName varchar(50), ssn varchar(20), ReqDate datetime2(0))
insert into #ssns values (1,'test,test','0001','20180621'),

if object_id('tempdb..#pt') is not null drop table #pt 
select a.*, b.patientSID, b.patientName, b.patientSSN, b.DeathDateTime

into #pt    
from #ssns a
join spatient.spatient b on b.patientname = a.fname 
where b.sta3n = 558 and RIGHT(b.patientSSN,4) = a.ssn

if object_id('tempdb..#ptappt') is not null drop table #ptappt
select a.*, c.locationName, d.stopCode, b.appointmentDateTime,  b.appointmentStatus

into #ptappt
from #pt a
left join LSV.D01_VISN06.cci_Appt_Appointment b on b.patientSID = a.patientSID and b.sta3n = 558
join dim.location c on c.locationSID = b.locationSID and c.sta3n = 558
join dim.stopCode d on d.stopCodeSID = c.primaryStopCodeSID and d.sta3n = 558

where isnull(b.AppointmentStatus,'Null') not in ('C', 'CA') 
and appointmentDateTime >= a.reqDate
and d.stopCode in ('323', '322', '350')

1 个答案:

答案 0 :(得分:0)

我找到了答案。您在联接上过滤where子句:

from #pt a
left join LSV.D01_VISN06.cci_Appt_Appointment b on b.patientSID = a.patientSID and   b.sta3n = 558 and 
isnull(b.AppointmentStatus,'Null') not in ('C', 'CA') 
and appointmentDateTime >= a.reqDate
left join dim.location c on c.locationSID = b.locationSID and c.sta3n = 558
left join dim.stopCode d on d.stopCodeSID = c.primaryStopCodeSID and d.sta3n = 558
and d.stopCode in ('323', '322', '350')