Question

I need to find the difference in averages between patient weights at different visits (time points), but I'm struggling with finding the "paired" averages:

I have 1 table (PHYS) containing patient weights at different visits:

PATIENT    VISIT       WEIGHT
1          Baseline    200
1          1 Month     190
1          2 Month     170
2          Baseline    300
2          1 Month     290
2          2 Month     280
3          Baseline    250
3          1 Month     230

My problem is that I only want to find the difference for paired data. For example, when calculating the amount of weight loss between the 2 month and Baseline visits, I would want to find the difference between the (average 2 Month weight) and the (average Baseline weight FOR ONLY THOSE PATIENTS WITH A 2 MONTH WEIGHT). In this example, the result should be AVG(170,280) - AVG(200,300) = -25 (since only patient 1 and 2 have 2 Month weights).

Here is what I have, but it calculates the difference based on all weights:

SELECT VISIT
  AVG(WEIGHT)
  -
(SELECT
  AVG(WEIGHT)
  FROM PHYS
  WHERE VISIT = 'BASELINE')
FROM PHYS
GROUP BY VISIT

My desired output would be (I know I need to add an ORDER BY):

VISIT      CHANGE FROM BASELINE
Baseline   0
1 Month    -13.3
2 Month    -25

Thank you and sorry for such a newb question.

Was it helpful?

Solution

You can do this with a join to the same table but only for the 'Baseline'. Then, the aggregation only aggregates the values that match, so you should get different baseline averages for the three groups (because the populations are different):

select p.visit, avg(p.weight) as avg_weight, avg(pbl.weight) as avg_blweight,
       (avg(p.weight) - avg(pbl.weight)) as change
from phys p join
     phys pbl
     on p.patient = pbl.patient and
        pbl.visit = 'Baseline'
group by p.visit;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top