2015-12-10 273 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