如何为给定数据创建范围

时间:2014-01-15 08:49:10

标签: sql sql-server date-range

如果可能,我们可以为年龄创建一个范围并显示相同的计数吗?

假设,范围在22到25之间:3,范围在26到30之间:5。

以下是我正在尝试执行此操作的人员表:

Age: 26 to 27, comments " post graduate"
Age: 28 to 30, comments "working and single"
Age: 31 to 33, comments " middle level manager and married"

Table name: persons

personid  lastname  firstname   age comments
1         Cardinal  Tom         22
2         prabhu    priya       33
3         bhandari  abhijeet    24
4         Harry     Bob         25
5         krishna   anand       29
6         hari      hara        31
7         ram       hara        27
8         kulkarni  manoj       35
9         joshi     santosh     28

1 个答案:

答案 0 :(得分:3)

SELECT COUNT(CASE WHEN AGE >= 26 AND AGE <= 27 THEN 1 ELSE NULL END) AS [total26To27]
      ,  COUNT(CASE WHEN AGE >= 28 AND AGE <= 30 THEN 1 ELSE NULL END) AS [total28T30]
      ,  COUNT(CASE WHEN AGE >= 31 AND AGE <= 33 THEN 1 ELSE NULL END) AS [total31T33]
FROM Persons