r/SQL•
Modest_Gaslight

How to work out an age using a specific date (not current date)?

DB2

So I have something that looks like this:

SELECT DISTINCT
bla
bla
bla
FROM viewA as A
RIGHT JOIN
viewB as B
ON id = id

I want to calculate an age from a given date, say 31/08/11, then put in age bands 16-19 and 20-24. Was thinking something like this:

CAST (DAYS(31/08/2011)-DAYS(DOB)/365.25 AS DEC(16,0) AS age
SELECT DISTINCT
bla
bla
bla
FROM viewA as A
RIGHT JOIN
viewB as B
ON id = id
CASE WHEN age <20 then '16-19'
WHEN age <25 THEN '20-24'
ELSE 'N/A' END AS 'age group'

But this doesn't work. And I don't think this is the best way to calculate age. Can someone help me tidy this up so it works and gives the correct age accurately please?

Posted Jun 26, 2023, 2:44 PM UTC

121
Loading comments…