我有以下T-SQL来计算年龄:
SELECT
Member_ID,
DATEDIFF(YY,DOB,GETDATE()) -
CASE
WHEN DATEADD(YY,DATEDIFF(YY,DOB,GETDATE()),DOB) > GETDATE() THEN 1
ELSE 0
END AS Age in Years
FROM MEMBER
WHERE YEAR(registration_date ) >= 2012
如何计算每个年龄段的会员ID数量?
答案 0 :(得分:1)
我会使用子查询或CTE来完成此操作。更容易理解:
SELECT AgeInYears, COUNT(*)
FROM (SELECT Member_ID,
(DATEDIFF(YY,DOB,GETDATE()) -
CASE WHEN DATEADD(YY,DATEDIFF(YY,DOB,GETDATE()),DOB) > GETDATE() THEN 1
ELSE 0
END) AS AgeinYears
FROM MEMBER
WHERE YEAR(registration_date ) >= 2012
) m
GROUP BY AgeInYears
ORDER BY 1;
答案 1 :(得分:0)
这样的事情:
SELECT
-- Member_ID, commented out
DATEDIFF(YY,DOB,GETDATE()) -
CASE
WHEN DATEADD(YY,DATEDIFF(YY,DOB,GETDATE()),DOB) > GETDATE() THEN 1
ELSE 0
END AS Age in Years
, count(member_id) membersWithThisAge
FROM MEMBER
WHERE YEAR(registration_date ) >= 2012
group by DATEDIFF(YY,DOB,GETDATE()) -
CASE
WHEN DATEADD(YY,DATEDIFF(YY,DOB,GETDATE()),DOB) > GETDATE() THEN 1
ELSE 0
END
member_id不能包含在select子句中。如果是,那么你会得到每个成员一个年龄的计数。