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我預期的結果