在一组Labtests中选择第一次和最后一次测试

时间:2017-04-05 10:53:10

标签: sql postgresql-9.1

我有一张表PatientLab我有一组测试如下

select ename, hiredate, sal,
decode(hiredate, 1980, sal*1.3, 1981, sal*1.1, 1982, sal*1.2,0) as bonus
from emp;

我想要的结果;

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

我正在使用postgresql 9

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用min和max

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