Full Outer Join in Access 同时计算项目
Full Outer Join in Access while counting the items
我正在尝试在 Access 中创建一个完整的外部联接,同时对项目进行计数并获取百分比。
这是我的代码:
SELECT Main.Draft, Count(Main.Draft) AS MainCount, (Count([Main.Draft])/(Select Count(Main.Draft) from Main)) AS Percentage
FROM Main LEFT JOIN Main_ChangeLog ON Main.ID = Main_ChangeLog.ID
GROUP BY Main.Draft;
UNION ALL
SELECT Main.Draft, Count(Main.Draft) AS MainCount, (Count([Main.Draft])/(Select Count(Main.Draft) from Main)) AS Percentage
FROM Main RIGHT JOIN Main_ChangeLog ON Main.ID = Main_ChangeLog.ID
WHERE (((Main.Date) Between [Forms]![Main Reports]![txtbegin] And [Forms]![Main Reports]![txtend]))
GROUP BY Main.Draft;
这是我的结果:
Version_1 1 0
Version_2 1 0
Version_3 3 0
Version_1 4 0
Version_2 3 0
这是我想要的结果:
Version_1 5 0.50
Version_2 4 0.15
Version_3 3 0.35
这是主要内容 table:
ID CreateDate FirstName LastName Draft
1 10/01/2020 First One Version_2
2 11/20/2020 Second Person Version_3
3 11/20/2020 Third Girl Version_3
4 11/21/2020 Fourth Boy Version_3
5 11/22/2020 Fifth Guy Version_1
这里是 Main_ChangeLog table:
ID CreateDate FirstName LasteName Draft
1 9/10/2020 First One Version_1
2 9/10/2020 Second Person Version_1
2 10/10/2020 Second Person Version_2
3 9/10/2020 Third Girl Version_1
3 10/10/2020 Third Girl Version_2
4 9/5/2020 Fourth Boy Version_1
4 10/10/2020 Fourth Boy Version_2
每次在 Main table 上更新记录时,以前的记录都会存储在 Main_ChangeLog 中。它有助于真正了解每个月创建了多少个版本。
我刚刚将我的代码修改为:
SELECT t.Draft, Count(t.Count) AS DraftCount, (Count(t.Draft)/(Select Count(t.Draft) from Main)) AS [Percentage]
FROM
(SELECT Main.Draft as Draft, Main.Draft as [Count]
FROM MainLEFT JOIN Main_ChangeLog ON Main.ID = Main_ChangeLog.ID
WHERE (((Main.Date) Between [Forms]![Main Reports]![txtbegin] And [Forms]![Main Reports]![txtend]))
UNION ALL
SELECT Main.Draft AS Draft, Main.Draft as [Count]
FROM MainRIGHT JOIN Main_ChangeLog ON Main.ID = Main_ChangeLog.ID
WHERE (((Main.Date) Between [Forms]![Main Reports]![txtbegin] And [Forms]![Main Reports]![txtend]))) AS t
GROUP BY t.Draft
现在我收到这个错误:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
谢谢。
这是通过两个查询完成它的一种方法:
- 第一个查询(我们称之为
qryMainData
)将使用UNION ALL
: 将所有版本数据连接在一起
SELECT ID, Draft, CreateDate FROM Main
UNION ALL
SELECT ID, Draft, CreateDate FROM Main_ChangeLog;
- 第二个查询将基于第一个,因为你想用查询1的整个结果集的总计数(
qryMainData
)来计算百分比:
SELECT Draft, Count(ID) as DraftQty, (SELECT COUNT(ID) FROM qryMainData) as TotalDraftQty,
ROUND(DraftQty/TotalDraftQty, 2) as DraftPercentage
FROM qryMainData
WHERE CreateDate Between [Forms]![Main Reports]![txtbegin] And [Forms]![Main Reports]![txtend]
GROUP BY Draft
MS Access 允许您在计算中使用字段别名。我还使用 ROUND
函数将结果四舍五入到小数点后两位。