2017-04-05 61 views
3

我有一個表PatientLab我有一組測試如下選擇第一個和最後一個測試組Labtests

patientid labtest  dateordered result 
100   cd4   1/1/14   500 
100   cd4   1/4/14   200 
100   cd4   1/5/15   800 
100   vl   1/4/14   564 
200   cd4   1/5/16   455 
200   cd4   1/6/16   678 
200   cd4   1/7/16   234 
200   cd4   1/8/16   356 
200   vl   1/7/16   1000 

我想要的結果的;

patientid FirstCD4  FirstCD4Date  LastCD4  LastCD4Date 
100   500   1/1/14   800   1/5/15 
200   455   1/5/16   356   1/8/16 

正在使用PostgreSQL 9

+1

你嘗試過什麼呢? – etsa

+0

我試圖'選擇patientid,dateordered,導致從PatientLab 其中(patientid)IN( 選擇patientid,最大值(dateordered)從PatientLab AS dateordered 其中LABTEST = 'CD4' 組由patientid )'是能夠只能得到最大值,但無法同時從最大值和最小值中獲得最大值和最小值 –

+0

對於患者只有一個CD4的情況,我們是否還應該包括一行以及我們所擁有的細節?對於那些沒有CD4的人也一樣嗎? – toonice

回答

2
with CTE as 
(
select p1.*, 
     row_number() over(partition by patientid order by dateordered asc) as r1, 
     row_number() over(partition by patientid order by dateordered desc) as r2 
from PatientLab p1 
where labtest = 'cd4' -- Case sensitive, thanks etsa 
) 
select C1.PatientID, 
     C1.result as FirstCD4, 
     C1.dateordered as FirstCD4Date, 
     C2.result as LastCD4, 
     C2.dateordered as LastCD4Date 
from CTE C1 
inner join CTE C2 
on C1.PatientID = C2.PatientID 
where C1.r1 = 1 
and C2.r2 = 1 
+0

它在SQL Server 2012中運行良好,但是無法在postgresql 9中複製此任何想法? @JohnHC –

+0

@ Shark-NeilFelyx窗口函數和CTE都應該在Postgres中工作,你會得到任何錯誤還是隻是沒有數據? – JohnHC

+0

我同意@JohnHC:它也應該在Postgresql中工作。 – etsa

0

您可以使用最小和最大

select a.patientid, min(a.result) as FirstCD4, min(dateordered) as FirstCD4Date 
    , max(a.result) as LastCD4, max(dateordered) as LastCD4Date 
    from (
select * from yourpatient where labtest = 'cd4') a 
group by a.patientid; 

你的表和細節Code

+0

結果與預期的結果不一樣,有時最短的日期可以有最大的結果。日期和結果是獨立的。即這是不是最小日期必須有最小結果的條件 –

相關問題