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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章