年龄间隔组计为SQL中的列变量

时间:2013-02-25 08:46:11

标签: sql

我正在尝试转换出生年份列表

  Id  | Birthyear 
 ------------------
   1  |   1984
   2  |   1945
   3  |   1996       
   4  |   1921
   5  |   1977
   6  |   1996
   7  |   1988
   8  |   1956
   9  |   1961
   10 |   1987

进入某些年龄段的组计数,作为列变量

  0-20  |  21-40  |  41-60 |  61 - 100
 -------------------------------------
   1    |    4    |    2   |     2

但我的努力是徒劳的

 declare @datum datetime
 set @date = convert(datetime, '20130225')      

 SELECT
 SUM(CASE WHEN datediff(d, Birthyear, @date)/365.25) < 20 THEN 1 ELSE 0 END) [0-20],

这有诀窍吗?

SQLFiddle

1 个答案:

答案 0 :(得分:2)

由于看起来你只有一年,我只会将当前年份作为整数进行比较:

;WITH Ages AS 
(
  SELECT YEAR(getdate()) - Birthyear AS Age
  FROM people
)
SELECT SUM(CASE WHEN Age BETWEEN 0 AND 20 THEN 1 ELSE 0 END) AS [0-20],
    SUM(CASE WHEN Age BETWEEN 21 AND 40 THEN 1 ELSE 0 END) AS [21-40],
    SUM(CASE WHEN Age BETWEEN 41 AND 60 THEN 1 ELSE 0 END) AS [41-60],
    SUM(CASE WHEN Age BETWEEN 61 AND 100 THEN 1 ELSE 0 END) AS [61-100]
FROM Ages

SQL Fiddle