我有一个带有ClientID(PK)的客户端表和带有日期/时间作为数据类型的DOB字段。我需要创建一个查询来训练年龄组,例如:
Age Group Count
18 – 24 2
25 - 35 1
36 - 45 2
46 - 55 5
56 - 65 0
66+ 2
Not stated 5
Total 17
我有以下sql查询:
SELECT DISTINCT Partition(DateDiff("yyyy",[DOB],Date())(DateSerial(Year(Date()),Month([DOB]),Day([DOB]))>Date()),19,66,8) AS Range,
Count(ClientsDetails.ClientID) AS CountOfAgeGroups
FROM ClientsDetails
GROUP BY Partition(DateDiff("yyyy",[DOB],Date())+(DateSerial(Year(Date()),Month([DOB]),Day([DOB]))>Date()),19,66,8);
它产生以下结果:
Range CountOfAgeGroup
:18 1
27:34 4
35:42 1
67: 1
有人可以指导我应该对查询做出哪些更改,或者可能建议最佳解决方案以达到预期效果,因为我对Access不太熟悉。
提前致谢。
这是我查询的第二部分。是否也可以使用参数搜索在两个日期之间找到年龄组。例如,如果我想在01/01/14和17/03/14之间找到年龄组。我使用Gord Thompson发布的解决方案尝试了以下方法,但它丢失了错误的表达式错误:
SELECT [%$##@_Alias].AgeGroup, Count(*) AS CountOfAgeGroup, Support.ClientID
FROM (SELECT Switch([Age] Between 18 And 24, "18-24", [Age] Between 25 And 35, "25-35", [Age] Between 36 And 45, "36-45", [Age] Between 46 And 55, "46-55",[Age] Between 56 And 65, "56-65",[Age] > 66, "66+") AS AgeGroup FROM (SELECT DateDiff("yyyy",[DOB],Date())-IIf(Format(Date(),"mmdd")<Format([DOB],"mmdd"),1,0) AS Age FROM ClientsDetails) AS [%$##@_Alias]) AS [%$##@_Alias], Support
GROUP BY [%$##@_Alias].AgeGroup,Support.ClientID
HAVING (((Support.ClientID) Between [Enter Start Date] And [Enter End Date]));
答案 0 :(得分:3)
如果我们从一个计算实际年龄的查询开始(基于[Date_of_Birth]字段和Date()
函数)
SELECT
DateDiff("yyyy",[Date_of_Birth],Date())-IIf(Format(Date(),"mmdd")<Format([Date_of_Birth],"mmdd"),1,0) AS Age
FROM Students
然后我们可以将其用作子查询并应用Switch()
函数(ref:here)为每个条目分配[AgeGroup]
SELECT
Switch([Age] Between 0 And 17, "0-17", [Age] Between 18 And 24, "18-24", [Age] Between 25 And 35, "25-35", [Age] > 35, "Over 35") AS AgeGroup
FROM
(
SELECT
DateDiff("yyyy",[Date_of_Birth],Date())-IIf(Format(Date(),"mmdd")<Format([Date_of_Birth],"mmdd"),1,0) AS Age
FROM Students
)
然后将整个内容包装在聚合查询中
SELECT
AgeGroup,
Count(*) AS CountOfAgeGroup
FROM
(
SELECT
Switch([Age] Between 0 And 17, "0-17", [Age] Between 18 And 24, "18-24", [Age] Between 25 And 35, "25-35", [Age] > 35, "Over 35") AS AgeGroup
FROM
(
SELECT
DateDiff("yyyy",[Date_of_Birth],Date())-IIf(Format(Date(),"mmdd")<Format([Date_of_Birth],"mmdd"),1,0) AS Age
FROM Students
)
)
GROUP BY AgeGroup
获得这样的结果
AgeGroup CountOfAgeGroup
-------- ---------------
0-17 5
18-24 12897
25-35 3537
Over 35 766