返回从存储的DOB中推断出的特定年龄的人数

时间:2014-01-08 13:44:18

标签: sql sql-server database

我正在使用以下查询返回所有存储的用户出生日期的年龄(以年为单位)。如果我可以基本上计算年龄,那么我可以生成一份报告。查询很粗糙,因此我很难理解我是如何做到这一点的,特别是因为聚合函数不能分配别名。

Select
    DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - 
    CASE WHEN
        DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP)
        > CURRENT_TIMESTAMP
    THEN 1
    ELSE 0 END as ageYears

from [database].[dbo].[users]

使用distinct关键字我可以返回年龄组,而不是实例,但我如何将其加入count

这个输出是理想的:

age | numUsers
18  | 1
19  | 3
20  | 7
21  | 1
22  | 9
23  | 2

3 个答案:

答案 0 :(得分:2)

只需使用CTE或子查询首先创建年龄,然后通过查询创建一个简单的组来计算它们:

; With Ages as (
    Select
        DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - 
        CASE WHEN
            DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP)
            > CURRENT_TIMESTAMP
        THEN 1
        ELSE 0 END as ageYears

    from [database].[dbo].[users]
)
SELECT ageYears,COUNT(*) as NumUsers
FROM Ages
GROUP BY ageYears

不需要子查询或CTE的替代方法是在GROUP BY子句中重复整个复杂表达式:

Select
    DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - 
    CASE WHEN
        DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP)
        > CURRENT_TIMESTAMP
    THEN 1
    ELSE 0 END as ageYears,
    COUNT(*) as numUsers
from [database].[dbo].[users]
group by
DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - 
    CASE WHEN
        DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP)
        > CURRENT_TIMESTAMP
    THEN 1
    ELSE 0 END as ageYears

就个人而言,我更喜欢以前的版本。

答案 1 :(得分:2)

你能试试吗,

Select X.age, sum (X.num) numUsers
From (
Select
    DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - 
    CASE WHEN
        DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP)
        > CURRENT_TIMESTAMP
    THEN 1
    ELSE 0 END age, 
    1 num

from [database].[dbo].[users]
) X
group by X.age

答案 2 :(得分:1)

测试数据

DECLARE @T TABLE (ID INT, DOB DATE)
INSERT INTO @T 
VALUES (1, '1940-01-01'),(2, '1940-01-01'),(3, '1985-01-01')
,(4, '1985-01-01'),(1, '1999-01-01'),(1, '1968-01-01')

<强>查询

SELECT     DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - 
    CASE WHEN
        DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP)
        > CURRENT_TIMESTAMP
    THEN 1
    ELSE 0 END  AS Age , COUNT(*) AS Total
FROM @T
GROUP BY DateDiff(YEAR, dob, CURRENT_TIMESTAMP) - 
    CASE WHEN
        DATEADD(year,DateDiff(YEAR, dob, CURRENT_TIMESTAMP),CURRENT_TIMESTAMP)
        > CURRENT_TIMESTAMP
    THEN 1
    ELSE 0 END  

<强>结果

╔═════╦═══════╗
║ Age ║ Total ║
╠═════╬═══════╣
║  14 ║     1 ║
║  28 ║     2 ║
║  45 ║     1 ║
║  73 ║     2 ║
╚═════╩═══════╝