Access 2010 - 使用Union All和Sum Iif查询以生成多个表中特定事件的总计数/总和

时间:2016-01-12 22:06:50

标签: sql database ms-access ms-access-2010

我有一个包含四个表的数据库:表1,2,3和& 4.每个表包含以下字段:ID(自动编号),日期(日期/时间),名称(文本)和项目(文本)

我创建了一个SQL查询,它使用Union All和Sum Iif表达式来检索" Apples"," Oranges"和" Pears"发生在每个人的“项目”列下。例如,当Query运行时,我希望查询向我提供日期,个人姓名以及" Apples"," Oranges"和/或的总计"梨"为日期和个人。 (2015年12月15日 - Dee Wolf - 15个苹果,10个橘子,20个梨)

问题:我的查询成功计算了所有4个表中的所有数据,但是它没有产生总数。相反,它为每张桌子提供一对一的计数。例如:表1将显示John有1个苹果和1个橙色,其中表2显示John有2个苹果和1个橙色。当我运行我的查询时,它会显示约翰有2个苹果,1个苹果,1个橙色和1个橙色(每个表的结果),但我想要它只是说约翰总共有3个苹果。

我已将此代码写入另一个数据库,它似乎产生了我想要的结果。但我不确定为什么我无法重现结果。我忽略了什么吗?

这是SQL:

SELECT Table1.Date, Table1.Name, Sum(IIf([Table1]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table1]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table1]![Item]="Pears",1,Null)) AS CountPears
FROM Table1
GROUP BY Table1.Date, Table1.Name
HAVING (((Table1.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table1.Name)))
UNION ALL
SELECT Table2.Date, Table2.Name, Sum(IIf([Table2]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table2]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table2]![Item]="Pears",1,Null)) AS CountPears
FROM Table2
GROUP BY Table2.Date, Table2.Name
HAVING (((Table2.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table2.Name)))
UNION ALL
SELECT Table3.Date, Table3.Name, Sum(IIf([Table3]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table3]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table3]![Item]="Pears",1,Null)) AS CountPears
FROM Table3
GROUP BY Table3.Date, Table3.Name
HAVING (((Table3.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table3.Name)))
UNION ALL
SELECT Table4.Date, Table4.Name, Sum(IIf([Table4]![Item]="Apples",1,Null)) AS CountApples, Sum(IIf([Table4]![Item]="Oranges",1,Null)) AS CountOranges, Sum(IIf([Table4]![Item]="Pears",1,Null)) AS CountPears
FROM Table4
GROUP BY Table4.Date, Table4.Name
HAVING (((Table4.Date) Between [SS/SS/SS] And [EE/EE/EE]) AND ((Table4.Name)));

1 个答案:

答案 0 :(得分:1)

HAVING ((...) AND ((Table1.Name)))

仍然没有多大意义......

要获取总计,请将整个查询包装到Sum()/ GROUP BY查询中:

SELECT [Date], [Name], Sum(CountApples) AS TotalApples, Sum(CountOranges) AS TotalOranges, 
                       Sum(CountPears) AS TotalPears
FROM (
    -- your UNION query goes here
)
GROUP BY [Date], [Name]

(无耻地从https://stackoverflow.com/a/32274957/3820271解除)