Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

oracle - sql grouping grades

I have a table for subjects as follows:

id  Subject Grade   Ext
100 Math    6       +
100 Science 4       -
100 Hist    3       
100 Geo     2       +
100 CompSi  1       

I am expecting output per student in a class(id = 100) as follows:

Grade   Ext StudentGrade
6       +       1
6               0
6       -       0
5       +       0
5               0
5       -       0
4       +       0
4               0
4       -       1
3       +       0
3               1
3       -       0
2       +       1
2               0
2       -       0
1       +       0
1               1
1       -       0

I would want this done on oracle/sql rather than UI. Any inputs please.

question from:https://stackoverflow.com/questions/65891377/sql-grouping-grades

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should generate rows first, before join them with your table like below. I use the with clause here to generate the 18 rows in your sample.

with rws (grade, ext) as (
select ceil(level/3), decode(mod(level, 3), 0, '+', 1, '-', null)
from dual 
connect by level <= 3 * 6
)
select r.grade, r.ext, nvl2(t.Ext, 1, 0) studentGrade 
from rws r
left join your_table t
on t.Grade = r.Grade and decode(t.Ext, r.Ext, 1, 0) = 1
order by 1 desc, decode(r.ext, null, 2, '-', 3, '+', 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...