从多个表中获取记录

时间:2014-03-10 07:01:23

标签: sql-server sql-server-2008 sql-server-2005 stored-procedures rdbms

我在数据库中有三个表,如下所示。我必须从这三个表中获取记录,以便RF_date应该在我将提供给查询的startdate和end date之间,然后page_id应该等于我将提供给查询的pagetype,最后一个是Assigned_To 。所以假设我发送“10/10/2003 12:00:00 AM”作为开始日期和10/10/2015 12:00:00作为结束日期和pagetype = 1然后我可能会从表中获得所有三条记录tblFrontUsers但是对于每个这个记录我在第二个表中有多个entires即“tblPatient”,所以我需要为每个用户获得最新的“Assigned_To”。例如:对于115,最新有“5”,对于116,最新为“1”,然后这5和1将它的名称存储在最后一个表格中,即tblUsers。 我正在尝试以下查询,但我发现很难得到所需的结果。 请帮忙。

    select tblFrontUsers .Name, tblFrontUsers .ID, tblFrontUsers.page_Id, tblPatient.Patient_ID , tblUsers.Name       
    tblPatient.Assigned_To   from tblFrontUsers left join tblPatient on tblPatient .ID=tblFrontUsers .ID  
left join tblUsers on tblUsers.Id = tblPatient .Assigned_To
    where tblFrontUsers .Rf_Date >= '12/17/2003 12:00:00 AM'
     and   tblFrontUsers .Rf_Date<='3/21/2014 12:00:00 AM' and tblFrontUsers.page_Id=1 
    and there can be search column with tblPatient.Assigned_To also. If it is present we need to get records only with this otherwise all. 




tblFrontUsers 

ID         Name           Rf_Date                         page_Id
115        Sandy          10/10/2013 12:00:00 AM            1
116        Javer          10/25/2013 12:00:00 AM            1
117        Felipe         10/22/2013 12:00:00 AM            1

tblPatient

Patient_ID      ID        Assigned_To
1               115         2
2               115         3
3               115         5
4               116         5
5               116         3
6               116         1

tblUsers
Id              Name       
1               Max
2               Sam
3               Harry
4               mary        
5               maria

1 个答案:

答案 0 :(得分:1)

select *
from tblFrontUsers Fo
left join (select max(Patient_ID) as Patient_ID,ID from tblPatient
            group by ID)P on P.ID=Fo.ID
inner join tblUsers U on U.Id=(select Assigned_To from tblPatient P1 where P1.Patient_ID=P.Patient_ID)
where (FO.Rf_Date between '12/17/2003 12:00:00 AM' and '3/21/2014 12:00:00 AM' 
and FO.page_Id=1)
order by Fo.[ID]

<强> SQL Fiddle

<强>更新

select *
from tblFrontUsers Fo
left join (select max(Patient_ID) as Patient_ID,ID from tblPatient
            group by ID)P on P.ID=Fo.ID
left join tblPatient P1 on P1.Patient_ID=P.Patient_ID
left join tblUsers U on U.Id=P1.Assigned_To
where (FO.Rf_Date between '12/17/2003 12:00:00 AM' and '3/21/2014 12:00:00 AM' 
and FO.page_Id=1)
--and p1.Assigned_To='2'
order by Fo.[ID]