我有两个查询:QueryA和QueryB。两者产生类似的结果。 QueryA:month,ID,countA和QueryB:month,ID,countB。
这些报告中的每一个都具有唯一的计数值,但两者之间将共享月份和ID。例如:
QueryA:
Month | ID | Count
Jan | 1 | 57
Feb | 1 | 63
Jan | 2 | 44
Feb | 2 | 11
QueryB:
Month | ID | Count
Jan | 1 | 22
Feb | 1 | 3
Jan | 2 | 99
Feb | 3 | 21
我需要一个产生以下内容的最终查询: QueryC:
Month | ID | CountA | CountB
Jan | 1 | 57 | 22
Feb | 1 | 63 | 3
Jan | 2 | 44 | 99
Feb | 2 | 11 |
Feb | 3 | | 21
请原谅任何缺乏格式。我是通过手机发帖的。
我需要一个最终输出,(1)提供两个查询中存在的Month + ID的合并结果以及任一查询中的那些...如果在QueryA中但不是B,如果在QueryB中但不是A.一体化结果(没有重复)。
答案 0 :(得分:0)
像这样创建联合查询:
SELECT ID
,Mnth AS [Month]
,Cnt
,"CountA" AS hdr
FROM QueryA
UNION
SELECT ID
,Mnth AS [Month]
,Cnt
,"CountB"
FROM QueryB
将其保存在名称下,例如qryAll1。 创建交叉表查询:
TRANSFORM Sum(qryAll1.Cnt) AS SumOfCnt
SELECT qryAll1.ID
,qryAll1.Month
FROM qryAll1
GROUP BY qryAll1.ID
,qryAll1.Month
PIVOT qryAll1.hdr;
同样,使用一个查询:
TRANSFORM Sum(u.Cnt) AS SumOfCnt
SELECT u.ID
,u.Month
FROM (
SELECT ID
,Mnth AS [Month]
,Cnt
,"CountA" AS hdr
FROM QueryA
UNION
SELECT ID
,Mnth AS [Month]
,Cnt
,"CountB"
FROM QueryB
) AS u
GROUP BY u.ID
,u.Month
PIVOT u.hdr;
创建联合查询
SELECT ID, Mnth as [Month], Cnt as CountA, 0 as CountB
FROM QueryA
UNION SELECT ID, Mnth as [Month], 0, Cnt
FROM QueryB;
将其另存为qryAll2并创建查询
SELECT qryAll2.ID
,qryAll2.Month
,Sum(qryAll2.CountA) AS SumOfCountA
,Sum(qryAll2.CountB) AS SumOfCountB
FROM qryAll2
GROUP BY qryAll2.ID
,qryAll2.Month
同样,使用一个查询:
SELECT u.ID
,u.Month
,Sum(u.CountA) AS SumOfCountA
,Sum(u.CountB) AS SumOfCountB
FROM (
SELECT ID
,Mnth AS [Month]
,Cnt AS CountA
,0 AS CountB
FROM QueryA
UNION
SELECT ID
,Mnth AS [Month]
,0
,Cnt
FROM QueryB
) AS u
GROUP BY u.ID
,u.Month
ORDER BY u.ID
,u.Month DESC;