我们想从具有多个表的Access数据库中计算 - 大约50个。
我们需要从每个表中的1列计算'QCPASS'这是一个复选框 - 如果通过该框的产品被检查是否失败然后没有。我们需要对EACH表进行计数,同时允许用户从每个表中存在的日期列指定日期范围。
我用查询尝试了这个但是我被告知查询无法选择,计算并执行日期范围。任何VBA帮助都会很棒。
导出到Excel会很棒,但任何结果都没问题。这是我创建的查询,它计算每个表传递和失败的列。我也不能用查询进行迭代,所以VBA似乎要走了:
SELECT "Table1" , Count('qcpass') AS column
FROM 5000028
GROUP BY [5000028].qcpass
union
SELECT "Table2",count('qcpass')
FROM 5000029
Group By [5000029].qcpass;
答案 0 :(得分:2)
您可以遍历数据库中的完整TableDefs
集合,并使用VBA创建查询。
警告: TableDefs
集合具有Access数据库系统表,因此您需要跳过此表。我建议你的方法是检查一个特定的表名前缀(在下面的代码中注明)。
public sub createMyBigUnionQuery()
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourFinalQuery", strSQL
db.close
exit sub
请注意,您可以定义所需的任何有效查询。以此作为提示,并根据您的特定需求进行调整。
希望这有助于你
通过@HansUp评论,如果您需要按日期过滤数据,您有两种选择:
where
上包含select
条件
我个人会选择选项1,这是一个示例代码:
public sub createMyBigUnionQueryWithDates(d0 as date, d1 as date)
dim db as DAO.database(), tbl as DAO.tableDef
dim strSQL as string, i as integer
set db = currentdb()
i = 1
for each tbl in db.TableDefs
if left(tbl.name, 1) = "5" then ' Check for a table name prefix
if i = 1 then
' The final spaces are important
strSQL = "select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
else
' The final spaces are important
strSQL = strSQL & " union all " & _
"select '" & tbl.Name & "' as table, count(qcpass) as column " & _
"from [" & tbl.Name & "] " & _
"where rowDate between " & cDbl(d0) & " and " &cDbl(d1) & " " & _
"group by qcpass "
end if
i = i + 1
end if
next tbl
db.createQueryDef "qryYourOtherFinalQuery", strSQL
db.close
exit sub
我使用cDbl(d0)
的原因是因为访问日期对区域设置很敏感,而且我遇到了很多麻烦。 Access(以及许多其他Microsoft产品)将日期存储为浮点数(整数部分是日期,小数部分是时间)。
警告的另一个词:如果您的日期不包括时间,则between
条件将起作用。但如果他们确实包括时间,那么我建议你改变where条件:
"where rowDate >= " & cDbl(d0) & " and rowDate < " & cDbl(d1 + 1)"