可以遍歷全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
請注意,您可以定義任何你想有效的查詢。以此作爲提示,並調整它以適應您的特定需求。
希望這有助於你
Adressing @HansUp評論,如果您需要按照日期來過濾你的數據,你有兩個選擇:
- 包括對創建的每個
select
的where
條件程序
- 將日期字段包含在您的查詢中並由其組成,並創建第二個查詢以從創建的查詢中過濾需要的數據。
我會親自去與選項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)"
此答案忽略了「按日期計數」部分的問題。 – HansUp
@HansUp在查詢中編寫適當的字段,where條件和group by條件不應該很難嗎? – Barranka
並不是真的,但在之前的問題中,OP說他不想爲他合併在一起的50個SELECT中的每一個寫一個WHERE。 – HansUp