我有一个生日字段作为日期类型,如果想按年龄范围对所有使用数据进行分组我已经有了以下sql代码来执行解决方案,但我需要与此对应的条件api查询。如何编写以下代码的条件查询??
WITH AgeData as
(
SELECT [Username],
[Birthdate],
DATEDIFF(YEAR, [Birthdate], GETDATE()) AS [AGE]
FROM @table
),
GroupAge AS
(
SELECT [Username],
[Birthdate],
[Age],
CASE
WHEN AGE < 30 THEN 'Under 30'
WHEN AGE BETWEEN 31 AND 40 THEN '31 - 40'
WHEN AGE BETWEEN 41 AND 50 THEN '41 - 50'
WHEN AGE > 50 THEN 'Over 50'
ELSE 'Invalid Birthdate'
END AS [Age Groups]
FROM AgeData
)
SELECT COUNT(*) AS [AgeGrpCount],
[Age Groups]
FROM GroupAge
GROUP BY [Age Groups];