我有一个实验室值表,我想查询并获得最后一个值和最近值之间的差异,如果它的> = 0.2。我该怎么做呢。这是我到目前为止的查询。任何帮助,将不胜感激。数据库是Oracle 10g。有关详细信息,请参见屏幕截图。
SELECT DISTINCT VISITLAB.DATEOFENTRY, VISITLAB.LABVALUE, VISITLAB.CODE
FROM(XCX.PATIENTVISIT PATIENTVISIT
INNER JOIN
XCX.MASTERPATIENT MASTERPATIENT
ON (PATIENTVISIT.MASTERPATIENTID = MASTERPATIENT.MASTERPATIENTID))
INNER JOIN
XCX.VISITLAB VISITLAB
ON (VISITLAB.MASTERPATIENTID = PATIENTVISIT.MASTERPATIENTID)
AND (VISITLAB.VISITNUMBER = PATIENTVISIT.VISITNUMBER)
WHERE (MASTERPATIENT.MASTERPATIENTID = 'xxxxxxxx')
AND (VISITLAB.CODE = 'UQN0')
AND (PATIENTVISIT.DISCHARGEDATE IS NULL)
AND (PATIENTVISIT.FACILITYCODE = 'x')
答案 0 :(得分:2)
您应该使用LAG anayltical函数来检索上一行中的值。
SELECT * FROM (
SELECT DISTINCT VISITLAB.DATEOFENTRY, VISITLAB.LABVALUE, VISITLAB.CODE,
(LAG(VISITLAB.LABVALUE) over (order by VISITLAB.DATEOFENTRY) - VISITLAB.LABVALUE) as DIFF
FROM(XCX.PATIENTVISIT PATIENTVISIT
INNER JOIN
XCX.MASTERPATIENT MASTERPATIENT
ON (PATIENTVISIT.MASTERPATIENTID = MASTERPATIENT.MASTERPATIENTID))
INNER JOIN
XCX.VISITLAB VISITLAB
ON (VISITLAB.MASTERPATIENTID = PATIENTVISIT.MASTERPATIENTID)
AND (VISITLAB.VISITNUMBER = PATIENTVISIT.VISITNUMBER)
WHERE (MASTERPATIENT.MASTERPATIENTID = 'xxxxxxxx')
AND (VISITLAB.CODE = 'UQN0')
AND (PATIENTVISIT.DISCHARGEDATE IS NULL)
AND (PATIENTVISIT.FACILITYCODE = 'x')
) INLINEVIEW
WHERE DIFF < .2
这不一定是您正在寻找的答案,但它演示了如何根据前一行中的值计算派生值。
答案 1 :(得分:0)
对于给定的CODE(例如UQN0),是否需要跨所有LABVALUE计算这些DIFF,这一点并不十分清楚。如果您对发布的屏幕截图中显示的最后两个感兴趣,那么也可以使用没有任何分析函数的纯SQL:
create table lab (
code varchar2(10),
date_of_entry date,
lab_value number(10,2)
);
insert into lab values('UQN0', trunc(sysdate) - 3, 0.98);
insert into lab values('UQN0', trunc(sysdate) - 2, 0.85);
insert into lab values('UQN0', trunc(sysdate) - 1, 0.90);
insert into lab values('UQN0', trunc(sysdate), 0.64);
commit;
select * from lab;
with last_results as (
select t.* from (
select * from lab where code = 'UQN0'
order by date_of_entry desc
) t where rownum <= 2
)
select t1.*
from last_results t1, last_results t2
where t1.lab_value - t2.lab_value >= 0.2;
如果不关心确保与其他数据库服务器的兼容性,那么LAG()函数显然是可行的方法。