表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个以上荣誉的人数,其它子项,就是每项荣誉在各个班级的人数
(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
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
type作为分组的列,class作为分组的行。id作为值,计数。不用写SQL语句。