TSQL - 单个查询中来自DOB的多个Count

时间:2012-04-05 22:17:08

标签: tsql

很抱歉,如果这是一个新手问题。是否可以在单个查询中使用不同的where条件获取Count列表。 基本上我试图得到一个列表,显示按年龄分列的申请人数量。 例 20 - 29 30 - 39 等

非常感谢, 安迪

2 个答案:

答案 0 :(得分:0)

;WITH AgeGroups AS (
SELECT
  CASE 
    WHEN FLOOR(DATEDIFF(DAY, DOB, GETDATE()) / 365.25 BETWEEN 20 AND 29 
      THEN '20 - 29'
    WHEN FLOOR(DATEDIFF(DAY, DOB, GETDATE()) / 365.25 BETWEEN 30 AND 39 
      THEN '30 - 39'
  END AS AgeGroup
FROM YourTable
)
SELECT
  AgeGroup,
  COUNT(*) AS AgeGroupCount
FROM AgeGroups
GROUP BY AgeGroup

答案 1 :(得分:0)

也许这样的事情对你有用

SELECT SUM(case where DATEDIFF(YEAR, [dob], GETDATE()) between 20 and 29 then 1 else 0) AS 'Age_20_29',
SUM(case where DATEDIFF(YEAR, [dob], GETDATE()) between 30 and 39 then 1 else 0) AS 'Age_30_39',
[etc.]
FROM myTbl