2014-12-19 32 views
0

我不知道如何去做这件事,我想我应该做一个交叉异常加入这里,但我不知道是否有更好的方法。SQL外部应用不返回结果我期望

我有这个破碎的查询,这将不会之一,因为第一个子查询返回运行3个结果,而不是,但通过阅读它,你应该明白我试图完成

select top 1 [weight], dateofvisit from WeeklyVisits where PatientId in 
(
select PatientId, StartDate, StartWeight from plans where PatientId in 
(select id from patients where clinicid=11 and id in 
(select distinct(patientid) from plans)) 
) order by dateofvisit desc 

我要回每个病人1个结果,其中一个结果将是最新的访问日期。

重量,dateofvisit,patientid,开始日期,visitdate

我想跨外连接因为其中的子查询不会允许我加入这些。

所以我至少尝试了一个无错误运行的跨外连接,但它并不仅仅显示临床ID为11的患者,它不显示最后的结果,而是显示空日期和体重。没有什么在这里工作;但是SQL对我来说不是一个很强的点。

select p.startdate, p.StartWeight, p.PatientId, x.DateOfVisit, x.[Weight] 
from plans p 
outer apply(
select top 1 [Weight], [DateOfVisit] from WeeklyVisits w 
where p.PatientId=w.PatientId and [weight] is not null and DateOfVisit is not null and p.PatientId in (
select id from patients where clinicid=11 and id in 
(select PatientId from plans)) 
)as x 

回答

2
select * from 
( select PatientId, StartDate, StartWeight, dateofvisit, 
      row_number() over (partition by PatientId order by dateofvisit desc) as rownum 
     from WeeklyVisits 
     join plans 
     on plans.PatientId = WeeklyVisits.PatientId 
     join patients 
     on patients.id = plans.id 
     and clinicid = 11) 
where rownum = 1 
+0

我不熟悉的关键字上,我得到一个不正确的语法上的关键字,所以我不知道如何调试它。 – mountaindweller 2014-12-19 01:06:19

+0

发布您正在运行的SQL Server版本(2205/2008等)某些版本支持它一些不要 – 2014-12-19 01:22:58

+0

这是来自内存 - 在msdn上搜索它。它可能是row_number()。我为了生活而做了sql。这是一个好方法。 – Paparazzi 2014-12-19 01:51:52