I am trying to extract data from two tables, first generating years registered for each person on a database, and then joining to another table to limit the age group, with the aim of getting a sum of total years registered for all people in the criteria. I currently get the error message
'arithmetic overflow error converting expression to data type’.
The obsdate variable is a 'YYYY-DD-MM' (date format), while yob is 'YYYY' (smallint) , but I thought that using YEAR(obsdate) had resolved this, and the issue may be elsewhere?
I saw about adding 'CAST(subquery.yearsreg AS BIGINT)' which gave me a far higher number than expected, and I'm not sure it achieved what I was hoping for?
SELECT SUM(subquery.yearsreg)
FROM (
SELECT id, yob,
(CASE
WHEN pat.deathdate IS NOT NULL AND pat.deathdate <= pat.regenddate THEN (YEAR(pat.deathdate)-YEAR(pat.regstartdate))
WHEN pat.deathdate IS NOT NULL AND pat.deathdate > pat.regenddate THEN (YEAR(pat.regenddate)-YEAR(pat.regstartdate))
WHEN pat.deathdate IS NULL AND pat.regenddate IS NOT NULL THEN (YEAR(pat.regenddate)-YEAR(pat.regstartdate))
ELSE YEAR(getdate())-YEAR(pat.regstartdate)
END) AS yearsreg
FROM Patient AS pat
) AS subquery
INNER JOIN Observation AS obs ON subquery.id = obs.id
WHERE obs.obsdate > '2004-12-31' AND obs.obsdate <= '2018-12-31'
AND ((YEAR(obs.obsdate))-subquery.yob) > 15 AND ((YEAR(obs.obsdate))-subquery.yob) < 45
yob? - maSTAShuFu