表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个以上荣誉的人头数COUNT,后面的就是各个荣誉的数量了SUM
select a.class,sum(d.total)as total,sum(e.表扬) as 表扬, sum(f.金奖) as 金奖,sum(g.银奖) as 银奖
from
表1 a,
(select id,iif(count(id)>=2,1,0) as total from 表2 group by id ) d ,
(select id,count(id)as 表扬 from 表2 where type='表扬' group by id) e ,
(select id,count(id)as 金奖 from 表2 where type='金奖' group by id) f ,
(select id,count(id) as 银奖 from 表2 where type='银奖' group by id) g
where a.id=d.id and a.id=e.id and a.id=f.id and a.id=g.id
group by a.class
这个查询语句 得出结果为:
Class total(>=2) 表扬 金奖 银奖
一(1) 1 2 1 1
就1行,其它班级没有了,请高手帮忙看看原因,谢谢!!
è¿è¡ä¸äºå¦~
追çåããaccessçé®é¢ï¼è¯è¯è¿æ ·åï¼
select a.class,sum(d.total)as total,sum(e.表æ¬) as 表æ¬, sum(f.éå¥) as éå¥,sum(g.é¶å¥) as é¶å¥
from 表1 a left outer join (select id,iif(count(id)>=2,1,0) as total from 表2 group by id ) d on a.id=d.id left outer join (select id,count(id)as è¡¨æ¬ from 表2 where type='表æ¬' group by id) e on a.id=e.id left outer join (select id,count(id)as éå¥ from 表2 where type='éå¥' group by id) f on a.id=f.id left outer join (select id,count(id) as é¶å¥ from 表2 where type='é¶å¥' group by id) g on a.id=g.id group by a.class
ä¸è¡å¦ï¼è¯æ³é®é¢~ åå¨ a.class è¿é
追çæleft outer jionå
¨æ¹æfull outer joinè¯è¯ï¼
å¦å¤ï¼å
åä¸ä¸ªçï¼ççå¯è¡å¦ï¼æ¯å¦aådçï¼