How to calculate AVG from two tablets
I am creating a database in SSMS and I am trying to calculate AVG from 2 columns from 2 tablets; I wrote :
;WITH combined AS
(
SELECT Datum_narodenia
FROM Zamestnanci
UNION ALL
SELECT Datum_narodenia
FROM ObčaniaSR
)
SELECT AVG(Datum_narodenia)
FROM combined;
But I got this error:
Msg 8117, Level 16, State 1
Operand data type date is invalid for avg operator.
I created table 1 :
CREATE TABLE Zamestnanci
(
id_Zamestnanca int not null,
Meno varchar(50) null,
Priezvisko varchar(50)null,
Adresa varchar(50) null,
Datum_narodenia date null,
PRIMARY KEY (id_Zamestnanca)
);
CREATE TABLE ObčaniaSR
(
id_Občana int not null,
Meno varchar(50) null,
Priezvisko varchar(50) null,
Adresa varchar(50) null,
Datum_narodenia date null,
Zápis_v_trestnom_registry varchar(50) null,
PRIMARY KEY (id_Občana)
);
Datum_narodenia
means Date_of_birth from witch I try to calculate AVG.
What is best way to calculate AVG age according to you? Thank you for your answers and advice.
Solution 1:
Pretty close calculation of age (lots of nitty-gritty in this answer) uses the difference in hours between the date and now, divided by the number of hours in a year (8766/24 = 365.25), which tries to roughly account for leap years; it is imperfect, but a pretty good trade-off IMHO between simple and right:
SELECT DATEDIFF(HOUR,'19860201',GETDATE())/8766;
So:
;WITH combined AS
(
SELECT Datum_narodenia
FROM Zamestnanci
UNION ALL
SELECT Datum_narodenia
FROM ObčaniaSR
)
SELECT AVG(DATEDIFF(HOUR, Datum_narodenia, GETDATE())/8766)
FROM combined;
Now, this does integer math, so you might instead want:
;WITH combined AS
(
SELECT Datum_narodenia
FROM Zamestnanci
UNION ALL
SELECT Datum_narodenia
FROM ObčaniaSR
)
SELECT CONVERT(DECIMAL(5,1),
AVG(DATEDIFF(HOUR, Datum_narodenia, GETDATE())/8766.0))
FROM combined;