考慮填充一個單獨的DATERANGE表中包含的所有範圍值,包括下令年,宿舍和月 。您可以在VBA建立與動態SQL查詢,這樣的表:
Public Sub PopulateTime()
Dim i As Integer, j As Integer, k As Integer
CurrentDb.Execute "CREATE TABLE DateRange (" _
& " [Year] Integer," _
& " [Quarter] Integer," _
& " [Month] Integer)", dbFailOnError
For i = 1989 To 2021
For j = 1 To 4
For k = 1 To 12
CurrentDb.Execute "INSERT INTO DateRange ([Year], [Quarter], [Month])" _
& " VALUES (" & i & ", " & j & ", " & k & ");"
Next k
Next j
Next i
End Sub
然後在這兩個表運行cross join總統和DATERANGE與日期過濾。使用這種查詢作爲源交叉表:
年
TRANSFORM Count(q.Year) AS CountOfYear
SELECT q.President
FROM
(SELECT p.ID, p.President, t.Year
FROM Presidents AS p,
(SELECT sub.[Year]
FROM DateRange sub
GROUP BY sub.[Year]) AS t
WHERE t.Year BETWEEN Year(p.StartDate) AND Year(p.EndDate)) AS q
GROUP BY q.ID, q.President
ORDER BY q.ID
PIVOT q.Year;
季度
TRANSFORM Count(q.Year) AS CountOfYear
SELECT q.President
FROM
(SELECT p.ID, p.President, t.Year, t.Quarter
FROM Presidents AS p,
(SELECT Year, Quarter
FROM DateRange sub
GROUP BY Year, Quarter) AS t
WHERE t.Year BETWEEN Year(p.StartDate) AND Year(p.EndDate)
AND DateSerial(t.Year, t.Quarter *3 - 2, 1) <= p.EndDate) AS q
GROUP BY q.ID, q.President
ORDER BY q.ID
PIVOT (q.Year & ' Q' & q.Quarter);
月
月是這裏有點廣泛,因爲Access表/查詢有一個最大的255此外,隨着數字字符串連接時一個月的排序不按數值順序,因爲兩位數字影響編號順序:。
要解決第一個問題,請運行兩個使用年份爲WHERE
的過濾器。以下運行直到2009年特朗普不輸出,然後運行從2010年到2021年相同的查詢。並解決第二個問題,請使用交叉的IN()
條款從1989-2009預先定義所有12個月多,許多列:
TRANSFORM Count(q.Year) AS CountOfYear
SELECT q.President
FROM
(SELECT p.ID, p.President, t.Year, t.Month
FROM Presidents AS p,
(SELECT Year, Month
FROM DateRange sub
GROUP BY Year, Month) AS t
WHERE t.Year BETWEEN Year(p.StartDate) AND Year(p.EndDate)
AND DateSerial(t.Year, t.Month, 1) <= p.EndDate) AS q
WHERE q.Year <= 2009
GROUP BY q.ID, q.President
ORDER BY q.ID
PIVOT (q.Year & ' ' & q.Month) IN ("1989 1", "1989 2", "1989 3", "1989 4", "1989 5",
"1989 6", "1989 7", "1989 8", "1989 9", "1989 10",
"1989 11", "1989 12", "1990 1", "1990 2", "1990 3",
"1990 4", "1990 5", "1990 6", "1990 7", "1990 8",
"1990 9", "1990 10", "1990 11", "1990 12",
...
"2008 1", "2008 2", "2008 3", "2008 4", "2008 5",
"2008 6", "2008 7", "2008 8", "2008 9", "2008 10",
"2008 11", "2008 12", "2009 1", "2009 2", "2009 3",
"2009 4", "2009 5", "2009 6", "2009 7", "2009 8",
"2009 9", "2009 10", "2009 11", "2009 12");
請編輯您的問題,加上預計結果 – Sami
謝謝薩米人,我添加了一張表,並獲得了理想的結果。 – Magnus