在Access SQL中组合子查询

时间:2016-12-28 15:01:16

标签: sql ms-access

我在Access 2007中有两个查询,它们共同提供一组中五个以上的子项数。我想在SQL中组合这些来进行一个查询。有人会在这个例子中演示语法吗?或者是否有更简单的方法来获得相同的结果?

第一个名为qryChildrenOverFive的查询是

SELECT 
 tblEventParticipants.EventParticipantsID, 
 DateDiff("yyyy", [tblChild.DoB],Date()) AS Age, 
 tblChild.DoB
FROM 
  tblEventParticipants 
  INNER JOIN (tblChild INNER JOIN tblChildParticipant 
  ON tblChild.ChildID = tblChildParticipant.ChildFK) 
  ON tblEventParticipants.EventParticipantsID = 
    tblChildParticipant.EventParticipantFK
WHERE (((tblEventParticipants.EventParticipantsID)=[CurrentID]) 
  AND ((DateDiff("yyyy",[tblChild.DOB],Date()))>5));

使用上述作为子查询的另一个是

SELECT qryChildrenOverFive.EventParticipantsID, 
  Count(qryChildrenOverFive.Age) AS NumOverFives
FROM qryChildrenOverFive
GROUP BY qryChildrenOverFive.EventParticipantsID;

作为一个子问题,为什么Access SQL不会在WHERE子句的第一个查询中使用别名'Age'?

1 个答案:

答案 0 :(得分:0)

1

只会返回日历年的差异。要计算年龄,您需要这样的函数:

DateDiff("yyyy", [tblChild.DoB],Date()) AS Age

然后:

Public Function AgeSimple( _
  ByVal datDateOfBirth As Date) _
  As Integer

' Returns the difference in full years from datDateOfBirth to current date.
'
' Calculates correctly for:
'   leap years
'   dates of 29. February
'   date/time values with embedded time values
'
' DateAdd() is used for check for month end of February as it correctly
' returns Feb. 28. when adding a count of years to dates of Feb. 29.
' when the resulting year is a common year.
' After an idea of Markus G. Fischer.
'
' 2007-06-26. Cactus Data ApS, CPH.

  Dim datToday  As Date
  Dim intAge    As Integer
  Dim intYears  As Integer

  datToday = Date
  ' Find difference in calendar years.
  intYears = DateDiff("yyyy", datDateOfBirth, datToday)
  If intYears > 0 Then
    ' Decrease by 1 if current date is earlier than birthday of current year
    ' using DateDiff to ignore a time portion of datDateOfBirth.
    intAge = intYears - Abs(DateDiff("d", datToday, DateAdd("yyyy", intYears, datDateOfBirth)) > 0)
  End If

  AgeSimple = intAge

End Function