[英]MS Access VBA SQL query using multiple AND operators fails?
I have a table (tbl_Avail) that shows availability for different people on certain dates and on certain parts of the particular day.我有一个表格(tbl_Avail),它显示了不同人在特定日期和特定日期的特定部分的可用性。 I am trying to make a query that counts the number of people available on multiple dates AND on certain times on those days.我正在尝试进行一个查询,计算多个日期和那些日子特定时间可用的人数。
tbl_Avail: (Pas1 & Pas2 (Boolean) indicates the 2 periods of the day that I am searching for availability for. True indicates available - false, not available) tbl_Avail:(Pas1 和 Pas2(布尔值)表示我正在搜索可用性的一天中的 2 个时段。True 表示可用 - false,不可用)
ID Student Date_Avail Pas1 Pas2
1 Joe 2020/08/09 x
2 Bob 2020/08/09 x
3 Pete 2020/08/09 x
4 Joe 2020/08/08 x x
5 Bob 2020/08/08 x
6 Pete 2020/08/08 x x
In this example I am searching for the number of people available (true) on date 2020/08/08 Pas2 AND on 2020/08/09 Pas1, but when I run the query it returns 0 - my expected result would be 2, as both Joe and Pete are available in Pas2 on the 8th and in Pas1 on the 9th.在此示例中,我正在搜索日期为 2020/08/08 Pas2 和 2020/08/09 Pas1 的可用人数(真),但是当我运行查询时它返回 0 - 我的预期结果为 2,如Joe 和 Pete 都可以在 8 日的 Pas2 和 9 日的 Pas1 中获得。
My query:我的查询:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim StudentsAvail As Long
Set rs = db.OpenRecordset("SELECT Count(*) AS StudentsTotal FROM tbl_Avail WHERE ((Pas1=true AND Date_Avail= #2020/08/09#) and (Date_Avail=#2020/08/08# AND Pas2=true))")
StudentsAvail = rs!StudentsTotal
If I change the query to only use ….如果我将查询更改为仅使用 ...。 WHERE Pas1=true and Date_Avail= #2020/08/09# for example, it works correctly.例如 WHERE Pas1=true 和 Date_Avail= #2020/08/09#,它可以正常工作。 There are no error codes - it just counts 0.没有错误代码 - 它只是计数 0。
I you have any idea as to what I am doing wrong, or have a better solution please let me know:-) Thank you.我对我做错了什么有任何想法,或者有更好的解决方案,请告诉我:-) 谢谢。 Peter彼得
One method is two levels of aggregation:一种方法是两个级别的聚合:
SELECT Count(*) AS StudentsTotal
FROM (SELECT Student
FROM tbl_Avail
GROUP BY Student
HAVING SUM(IIF(Pas1 = true AND Date_Avail = #2020/08/09#, 1, 0)) > 0 AND
SUM(IIF(Pas2 = true AND Date_Avail = #2020/08/08#, 1, 0)) > 0
) as s;
The subquery returns the students with both conditions true.子查询返回两个条件都为真的学生。 If uses a HAVING
clause because the conditions are true on different rows. If 使用HAVING
子句,因为条件在不同的行上为真。
The outer query counts the students.外部查询计算学生数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.