oracle分组关联统计,没有记录则显示0

数据如下

A表 atab
id name
1 张三
2 李四
3 王五

– B表 btab
a_id score
1 8
1 6
1 10
2 10
2 10
2 3

结果展示

统计他们得过几次10分
name result
张三 1
李四 2
王五 0
合计 3

**

sql:

**
方法一(比较麻烦):
select * from (
select name,sum(case when score=‘10’ then 1 else 0 end) result
from atab a,btab b where a.id=b.a_id group by a.name )
union all
select a.name,0 from atab a where not exists
(select * from btab b where a.id=b.a_id )
union all
select ‘合计’,
sum(case when score=‘10’ then 1 else 0 end) result
from btab

方法二:
select c.name,sum(case when c.score=‘10’ then 1 else 0 end) result from (
select name,nvl(score,0) score from atab a left join btab b on a.id=b.a_id) c
group by c.name
union all
select ‘合计’,
sum(case when score=‘10’ then 1 else 0 end) result
from btab

猜你喜欢

转载自blog.csdn.net/qq_38949960/article/details/89922381