Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in two row values of the same table

I have a lab values table that I would like to query and get the difference between the last value and the most recent value if its >= 0.2. How do I go around doing that. Here is the query I have so far. Any help would be appreciated. Database is Oracle 10g. See screenshot for details.

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')

enter image description here

like image 861
Shaji Avatar asked Nov 05 '22 21:11

Shaji


1 Answers

You should use the LAG anayltical function to retrieve a value in the previous row.

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

This isn't necessarily the answer you are looking for but it demonstrates how I can compute a derive a value for a column based on the value in a previous row.

like image 66
maple_shaft Avatar answered Nov 09 '22 08:11

maple_shaft