MS Access - 聚合查询问题

时间:2015-03-29 20:35:15

标签: sql ms-access relational-database

我有一个数据库,可根据学生参加活​​动来跟踪学生的社区服务时间。这种关系是正确建立的,但我遇到的问题是聚合查询。

这是我试图做的逻辑:

if(ActivityAttendance.Attended) == 1
   Affiliates.completedHours += Activities.creditHours

(This is just supposed to be more of a pseudo code)

ACTIVITYATTENDANCE是拥有Attended“yes / no”字段的表的名称。 CompletedHours是AFFILIATES表中的一个字段。

我试过找到一个解决方案,但似乎我在网上找到的所有内容都是能够总结是的数量和不是的数量。为了更好地理解,我附上了这段关系的图片。

这是可以使用基本Access功能完成的,还是有SQL解决方案?

由于我是新手,因此无法直接发布图像,但我已在此处上传:

http://s22.postimg.org/g0r53vgtd/Capture.png

1 个答案:

答案 0 :(得分:1)

在聚合查询的SELECT行中使用带有Sum的IIF():

SELECT Affiliates.StudentID, Affiliates.[First Name], Affiliates.[Last Name], 
Sum(IIF(ActivityAttendance.Attended = True, Affiliates.[Completed Hours], 0)) As AttendedServiceHours
FROM Affiliates 
INNER JOIN ActivityAttendance ON Affiliates.StudentID = ActivityAttendance.StudentID
GROUP BY Affiliates.StudentID, Affiliates.[First Name], Affiliates.[Last Name]

或者,您可以在聚合查询中使用WHERE子句:

SELECT Affiliates.StudentID, Affiliates.[First Name], Affiliates.[Last Name], 
Sum(Affiliates.[Completed Hours]) As AttendedServiceHours
FROM Affiliates 
INNER JOIN ActivityAttendance ON Affiliates.StudentID = ActivityAttendance.StudentID
WHERE ActivityAttendance.Attended = True
GROUP BY Affiliates.StudentID, Affiliates.[First Name], Affiliates.[Last Name]
相关问题