access SQL 多表查询统计问题,烦请帮忙看一下,谢谢你!

表1 (加了个班级)
Class name id
一(1) 张三 10001
二(6) 李四 10004
三(4) 王二 10005

。。。。

表二
id type
10001 表扬
10001 表扬
10004 金奖
10001 金奖
10005 银奖
10004 表扬
10001 银奖

最终查询结果如下表
Class total(>=2) 表扬 金奖 银奖
一(1) 1 2 1 1
二(6) 0 2 1 1
三(4) 0 1

说明:是按照班级进行统计查询,其中TOTAL 是显示该班级同时获得2个以上的人数
total 是各班级有2个以上荣誉的人数,其它子项,就是每项荣誉在各个班级的人数

第1个回答  2012-10-31
select a.class,
(select count(*) from biao2 c where a.id = c.id group by c.id having count(*)>=2) as 'total>=2',
sum(IIf(b.type = '表扬',1,0)) as 表扬,
sum(IIf(b.type = '金奖',1,0)) as 金奖,
sum(IIf(b.type = '银奖',1,0)) as 银奖
from biao1 a inner join biao2 b on a.id = b.id
group by a.class ,a.id
第2个回答  2012-10-31
和之前的写法类似,测试一下

select a.class,
sum(iif(select count(*) from table2 c where a.id = c.id >= 2,1,0)) as total,
sum(IIf(b.type = '表扬',1,0)) as 表扬,
sum(IIf(b.type = '金奖',1,0)) as 金奖,
sum(IIf(b.type = '银奖',1,0)) as 银奖
from table1 a inner join table2 b on a.id = b.id
group by a.class追问

sum(IIf((select count(*) from 表2 c where a.id = c.id)>=2,1,0)) as total, 这句有问题,其它句没问题

追答

试试这个

select a.class,
count(d.id) as total,

sum(IIf(b.type = '表扬',1,0)) as 表扬,
sum(IIf(b.type = '金奖',1,0)) as 金奖,
sum(IIf(b.type = '银奖',1,0)) as 银奖
from table1 a inner join table2 b on a.id = b.id
left join ( select id from table2 group by id having count(*) >= 2) as d on a.id = d.id
group by a.class

追问

a.id = b.id
left join ( select id from table2 group by id having count(*) >= 2) as d on a.id = d.id

你好,提示上门这句语法有问题,麻烦你了~

追答

打个括号试下
select a.class,
count(d.id) as total,
sum(IIf(b.type = '表扬',1,0)) as 表扬,
sum(IIf(b.type = '金奖',1,0)) as 金奖,
sum(IIf(b.type = '银奖',1,0)) as 银奖
from (table1 a inner join table2 b on a.id = b.id)
left join ( select id from table2 group by id having count(*) >= 2) as d on a.id = d.id
group by a.class

追问

可以运行,但结果TOTAL 数值不对

Class total(>=2) 表扬 金奖 银奖
一(1) 4 2 1 1
二(6) 2 1 1 0
三(4) 0 0 0 1

total 好像计算的是总数,大于2的才显示出来

问题还是处在 TOTAL 的计算,麻烦你帮忙研究一下,谢谢~

追答

select a.class,
count(distinct d.id) as total,
sum(IIf(b.type = '表扬',1,0)) as 表扬,
sum(IIf(b.type = '金奖',1,0)) as 金奖,
sum(IIf(b.type = '银奖',1,0)) as 银奖
from (table1 a inner join table2 b on a.id = b.id)
left join ( select id from table2 group by id having count(*) >= 2) as d on a.id = d.id
group by a.class

来自:求助得到的回答本回答被网友采纳
第2个回答  2012-10-31
使用Access里的交叉表查询就可以。
type作为分组的列,class作为分组的行。id作为值,计数。不用写SQL语句。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网