I have a database of patients with a VITALS
table. This table contains a unique patient ID (PATID)
per patient and a height variable (HT)
. A single patient may have >1
height recorded.
I'm trying to return a count of unique PATIDs
within and across height ranges (e.g., 68-72", 72-76", etc.)
. Each PATID
should be counted *only once*
. However what I'm finding is that if a patient has multiple heights recorded, they'll be counted once within a range, but if their height crosses ranges, they'll be counted twice - once in each range.
E.g., if a patient has height recorded as 68, 72, and 73 they'll be counted once in the 68-72 range and once in the 72-76 range. I can tell this is happening because we have 3054 unique PATIDs, but the sum of the counts returned by the query is >5000.
My code is:
SELECT
CASE
when "HT" >0 and "HT" <=4 then '0-4'
when "HT" >4 and "HT" <=8 then '4-8'
when "HT" >8 and "HT" <=12 then '8-12'
when "HT" >12 and "HT" <=16 then '12-16'
when "HT" >16 and "HT" <=20 then '16-20'
when "HT" >20 and "HT" <=24 then '29-24'
when "HT" >24 and "HT" <=28 then '24-28'
when "HT" >28 and "HT" <=32 then '28-32'
when "HT" >32 and "HT" <=36 then '32-36'
when "HT" >36 and "HT" <=40 then '36-40'
when "HT" >40 and "HT" <=44 then '40-44'
when "HT" >44 and "HT" <=48 then '44-48'
when "HT" >48 and "HT" <=52 then '48-52'
when "HT" >52 and "HT" <=56 then '52-56'
when "HT" >56 and "HT" <=60 then '56-60'
when "HT" >60 and "HT" <=64 then '60-64'
when "HT" >64 and "HT" <=68 then '64-68'
when "HT" >68 and "HT" <=72 then '68-72'
when "HT" >72 and "HT" <=76 then '72-76'
when "HT" >76 and "HT" <=80 then '76-80'
when "HT" >80 and "HT" <=84 then '80-84'
when "HT" >84 and "HT" <=88 then '84-88'
when "HT" IS NULL then 'Null'
else '>88'
END AS "Height Range",
COUNT(DISTINCT vital."PATID") AS "Count"
FROM dbo."VITAL" vital
GROUP BY 1;