Average date of birth from a single table where the column's date format is '01-JAN-2001'. Looking to return total count of users, and the average DOB YEAR (oracle sql)
mock table:
|User_ID|birth_date|
|123|01-JAN-2001|
|123|01-JAN-2001|
|123|01-JAN-2001|
Assuming your intention is to just average the year, you can parse it to a date, extract the year and average it as a number:
SELECT COUNT(*), AVG(EXTRACT(YEAR FROM TO_DATE(birth_date, 'dd-mon-yyyy'))
FROM users
(Oracle 12c:) Test table and data:
create table dt (
userid_ number generated always as identity ( start with 123 )
, d_ date
);
begin
for i in 1 .. 15
loop
insert into dt ( d_ ) values (
to_date ( trunc( dbms_random.value( 2446067, 2458100 ) ), 'J' )
) ;
end loop;
end;
/
SQL> select userid_, to_char( d_, 'DD-MON-YYYY' ) dob from dt;
USERID_ DOB
---------- --------------------
123 19-JUN-2000
124 06-OCT-2005
125 27-JAN-2012
126 09-JUL-2003
127 23-JUL-2010
128 07-FEB-1992
129 20-DEC-2002
130 19-MAY-2002
131 23-FEB-1990
132 26-DEC-1990
133 19-JUN-1999
134 16-DEC-1994
135 13-APR-2017
136 31-MAR-2000
137 23-MAY-1987
Query and result:
select
count(*) user_count
, trunc( avg( extract( year from d_ ) ) ) avg_dob_year
from dt ;
USER_COUNT AVG_DOB_YEAR
---------- ------------
15 2000
(Not taking "days" into account, just "years").
When using the method suggested by @mathguy
"... It can be calculated by subtracting a fixed date, like 2000/01/01, from all dates, taking the average of the differences, and adding it to the fixed date."
... this may be a query we could start with (I'm sure it can be refined):
select
count(*) usercount
, to_date( '2000/01/01', 'YYYY/MM/DD' ) fixeddate
, avg( differences ) difftofixed
, to_date('2000/01/01', 'YYYY/MM/DD' ) + avg( differences ) fixedplusdiff
, extract( year from ( to_date('2000/01/01', 'YYYY/MM/DD' ) + avg( differences ) ) ) dob_year
from (
select
d_ - to_date( '2000/01/01', 'YYYY/MM/DD' ) differences
from dt
);
-- result
USERCOUNT FIXEDDATE DIFFTOFIXED FIXEDPLUSDIFF DOB_YEAR
15 01-JAN-00 250.6 07-SEP-00 2000
I don't know why you're trying to get the average date but I think it would go something like this :
“SELECT COUNT(user_id), AVG(EXTRACT(YEAR FROM TO_DATE(birth_date, 'dd-MM-yyyy'))
FROM users”
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.