0

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

  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

4

1 回答 1

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小提琴

于 2013-02-25T08:51:13.133 回答