我正在尝试为人口统计目的选择特定电影租客的平均年龄。
我的数据类似于
Movies
movie_id movie_title
1 Spider Man
2 Avengers
3 Thor
Customers
customer_id customer_dob
1 1989-03-05
2 1994-02-12
3 2001-05-01
Customer_rentals
rental_id customer_id movie_id
1 1 1
2 1 3
3 2 2
4 2 1
5 3 1
我想看到的是
Title Avg_Age
Spider Man 25
Avengers 26
Thor 31
我试过以下
select m.movie_title as Title, avg(all_ages.age) as avg_age
from
movies m,
(select ((0 + convert(char(8), getdate(),112) - convert(char(8),c.customer_dob,112)) / 10000) as age
from customers c, movies m, customer_rentals cr
where m.movie_id=cr.movie_id
and cr.customer_id=c.customer_id) all_ages
group by m.movie_title
这给了我
Title Avg_Age
Spider Man 25
Avengers 25
Thor 25
它似乎取了所有年龄段的平均值并将其作为每部电影的平均值返回,我不确定为什么会这样