在单个表上显示两组或更多组聚合函数

时间:2014-03-15 16:28:46

标签: sql ms-access

我试图显示许多计数函数的结果,这些函数由不同的标准并排区分。

select *
from
(SELECT a.location, count(b.description)
from locations.a left join status b on a.zone =b.zone
where b.date_issued = #1/3/2012#
group by a.location) X
inner join
(SELECT a.location, count(b.description)
from locations.a left join status b on a.zone =b.zone
where b.date_issued = #1/2/2012#
group by a.location) Y
on X.zone = Y.zone;

我不能在主选择中引用X和Y,因为MS访问不断询问我参数值,如果我使用Select * i得到来自cluase的错误

请帮助

2 个答案:

答案 0 :(得分:0)

您想要使用条件聚合。从使用#作为日期常量,我猜你正在使用Access:

SELECT a.location,
       sum(iif(b.date_issued = #1/3/2012#, 1, 0) as val_20130103,
       sum(iif(b.date_issued = #1/2/2012#, 1, 0) as val_20130102
from locations.a left join
     status b
     on a.zone =b.zone
group by a.location;

通用SQL将使用case

SELECT a.location,
       sum(case when b.date_issued = #1/3/2012# then 1 else 0 end) as val_20130103,
       sum(case when b.date_issued = #1/2/2012# then 1 else 0 end) as val_20130102
from locations.a left join
     status b
     on a.zone =b.zone
group by a.location

答案 1 :(得分:0)

试试这个?

select *
from
(SELECT a.location, count(b.description) as Count, a.Zone
from locations a 
left join status b on a.zone =b.zone
where b.date_issued = #1/3/2012#
group by a.location) X
inner join
(SELECT a.location, count(b.description) as Count, a.Zone
from locations a 
left join status b on a.zone =b.zone
where b.date_issued = #1/2/2012#
group by a.location) Y
on X.zone = Y.zone;