我知道这应该是非常简单的,但我有心理障碍。我在SQL Server 2008数据库中有三个表:
用户:
User_Visits:
站点
我需要一个SQL语句来获取访问者平均年龄在40-50岁之间的网站数量。
提前致谢!
答案 0 :(得分:1)
select count(*) as SiteCount
from (
select avg(datediff(year, U.BirthDate, UV.Visit_Date)) as AvgAge
from Users as U
inner join User_Visits as UV
on U.ID = UV.User_ID
group by UV.Site_ID
) as T
where AvgAge >= 40 and
AvgAge < 50
答案 1 :(得分:0)
让我试试:
SELECT siteID, AVG(YEAR(GETDATE()) - YEAR(birthdate)) as avg_age,
FROM users_visits JOIN users ON users.ID = users_visits.userID
GROUP BY siteID HAVING avg_age BETWEEN 40 AND 50
这将返回您感兴趣的所有网站。要获得计数,您需要将count(siteID)
放入SELECT
部分,并将avg_age
的定义移至HAVING子句。