Explanation
After completing your answers and reading your interpretations of this question, I must add the following.
- I need to create the whole BMI story, not one value.
- Each value in both tables should be associated (if possible) with the corresponding value in another table.
Simple problem
When entering into PatientHeight, calculate the body mass index (BMI) with all entries in PatientWeight whose EntryDate is between the current PatientHeight EntryDate and the previous PatientHeight EntryDate. This is true if there are no EntryDates in PatientWeight and then "EntryDates" in PatientHeight. In this case, use the latest PatientHeight entry to calculate BMI.
For each entry in PatientHeight, calculate the body mass index (BMI) with all the corresponding relevant values ββin PatientWeight.
Some logic:
- PatientHeight EntryDate is <= PatientWeight EntryDate when mating
- PatientHeight has a one-to-many relationship with PatientWeight
- PatientHeight should take into account the EntryDate of the previous PatientHeight and use it as the lower bound when matching EntryDates in PatientWeight
I have a function to calculate BMI, it's just a question of how best to combine data from two tables.
Note. This must be done using a stored procedure, and I cannot modify the tables
Patientheight
Personid
Entrydate
Inches
9783 | 01/01/2010 | 75in
9783 | 01/01/2009 | 74in
Patientweight
Personid
Entrydate
Pounds
9783 | 01/01/2011 | 179lbs
9783 | 01/01/2010 | 175lbs
9783 | 12/01/2010 | 174lbs
9783 | 11/01/2010 | 178lbs
9783 | 01/01/2009 | 174lbs
9783 | 12/01/2009 | 174lbs
9783 | 11/01/2009 | 178lbs
PatientWeight PatientHeight, , - ?
:
9783 | 01/01/2011 | 75in | 178lbs
9783 | 01/01/2010 | 75in | 175lbs
9783 | 12/01/2010 | 75in | 174lbs
9783 | 11/01/2010 | 75in | 178lbs
9783 | 01/01/2009 | 74in | 174lbs
9783 | 12/01/2009 | 74in | 174lbs
9783 | 11/01/2009 | 74in | 178lbs
ββ . , .
Insert Into @PatientWeightRet
Select
*
From
(
Select
TransactionID,
EncounterID,
EntryDate,
ISNULL(CONVERT(NUMERIC(18,2),dbo.fnBmi(Inches, Pounds)), -1) AS BMI
From
(
Select Distinct
W.TransactionID,
W.PatientID,
W.EntryDate,
W.EncounterID,
W.Pounds,
(
Select Top 1
H.Inches
From
@PatientHeight AS H
Where
H.EntryDate <= W.EntryDate
AND W.EntryDate >
(
ISNULL
(
(
Select Top 1
EntryDate
From
@PatientHeight
Where
EntryDate < H.EntryDate
Order BY EntryDate Desc, TransactionID DESC
)
, '01/01/1800')
)
Order By H.EntryDate Desc, H.TransactionID DESC
) AS Inches
From
PatientWeight AS W
Where
PatientID = @PatientID
AND Active = 1
) tmp
) tmp2
Where
BMI != -1
Order By EntryDate DESC, TransactionID DESC