2015-12-10 207 views
0

我有一个关于SQL Server的问题。需要帮助在SQL Server中查询

表:patient

pn | hospid | doj 
------------------------ 
1 | 10 | 2015-10-14 
1 | 10 | 2015-05-14 
1 | 10 | 2015-08-12 

第二表:patientrefs

sdate  | edate  | codes | descripton | pn | hospid 
------------------------------------------------------------- 
2015-01-01 | 2015-09-30 | 500 | active  | 1 | 10 
2015-01-01 | 2015-09-30 | 501 | inactive | 1 | 10 
2015-10-01 | 2016-03-31 | 500 | activestill | 1 | 10 
2015-10-01 | 2016-03-31 | 501 | inactive | 1 | 10 
2013-03-09 | 2013-09-12 | 300 | inactive | 1 | 10 

两个表公共列pn + hospid和相关SDATE和patientrefs表的EDATE之间DOS患者表。

而在patientrefs表descritpton =无活性的并且条件之间日期满足然后代码我们考虑inactivecodes

在patientrefs表descritpton <>无活性的并且条件之间日期满足然后我们考虑在此基础上上述activecodes

码表我想这样的输出:

pn|hospid|doj  |inactivecodes| activecodes 
------------------------------------------------ 
1 |10 |2015-05-14 | 501  | 500 
1 |10 |2015-08-12 | 501  | 500 
1 |10 |2015-10-14 | 501  | 500 

我想是这样的:

select 
    a.pn, a.hospid, a.doj, 
    case when b.descripton <> 'inactive' then b.codes end activecodes, 
    case when b.descripton = 'inactive' then b.codes end inactivecodes 
from 
    patient a 
left join 
    patientrefs b on a.pn = b.pn and a.hospid = b.hospid 
        and a.doj between b.sdate and b.edate 

但该查询未返回预期结果。

我试过另一种方式

select 
    a.pn, a.hospid, a.doj, b.codes as inactivecodes 
from 
    patient a 
left join 
    patientrefs b on a.pn = b.pn and a.hospid = b.hospid 
        and a.doj between b.sdate and b.edate 
where 
    b.descripton = 'inactive' 

select 
    a.pn, a.hospid, a.doj, b.codes as activecode 
from 
    patient a 
left 
    patientrefs b on a.pn = b.pn and a.hospid = b.hospid 
        and a.doj between b.sdate and b.edate 
where 
    b.descripton <> 'inactive' 

这里各个查询返回预期的结果,但我需要主动和inactivecodes在上述预期的输出格式。

请告诉我如何编写查询来获取在SQL Server我预期的结果

回答

0

为此,您可以使用条件汇总:

SELECT 
    p.pn, 
    p.hospid, 
    p.doj, 
    inactivecodes = MAX(CASE WHEN pr.description = 'inactive' THEN pr.codes END), 
    activecodes  = MAX(CASE WHEN pr.description = 'active' THEN pr.codes END) 
FROM patient p 
LEFT JOIN patientrefs pr 
    ON p.pn = pr.pn 
    AND p.hospid = pr.hospid 
    AND p.doj BETWEEN pr.sdate AND pr.edate 
GROUP BY 
    p.pn, p.hospid, p.doj