SQL help

Status
Not open for further replies.

jx3000

Ars Tribunus Militum
2,571
I am doing an assignment for school, I hope someone can help.

I have to convert the following query which is using joins, into one that uses nested queries.

Original Query using Joins
---------------------------
select distinct s.sname, attend, sum(mark)
from stud s, result r, unit u
where s.sno = r.sno
and r.ucode = u.ucode
and u.uname = 'Practical Physical Endurance'
group by sname, attend

--------------------------------------
This is my attempt to solve it (with nested queries)

select distinct s.sname, s.attend, sum(r1.mark)
from stud s, result r1
where (s.sno, r1.mark) in

(select r2.sno, r2.mark
from result r2
where r2.ucode in

(select u.ucode
from unit u
where uname = 'Practical Physical Endurance'
)
)
group by s.sname, s.attend
 
(I'll be vague, since this is homework)

I assume that you're trying to get a result like:

Student Name, Something (Attend), Number of Times student attended.

With a subquery, you don't need to do any grouping. Write a normal query that would return all the students, and then, for your "Number of times attended" column, do a subquery that executes a count on the result and unit tables.

-H
 

jx3000

Ars Tribunus Militum
2,571
Sorry I can't explain that well.

I have two queries above, the top one is part of the question, and the bottom one is my solution. The place where I have written sum(r1.mark) is the only column return an incorrect result. Instead of only summing the marks for the student (sname), it sums all rows in the column of the table "result". Notice how I have set my subqueries. I am getting the correct student names(sname) and Attendance type (attend) which return P for part time and F for full time.

If no one can help me get that sum(r1.mark) to be related to the subquery structure, then don't worry about it. The assignment is due tomorrow, and only worth 2 marks anyway.
 
Ah, I see. So, your problem is you're doing your sum in the wrong place. You want to sum in the subquery, not in the main query. That way, it will be executed for each student, not for all the students. Also, you need to link your subquery to your main query; you seem to have gotten halfway there by referring to the result table twice with two different aliases, but you need to link them together in the subquery. And, you should be selecting on ucode = 'Practical Physical Endurance' in your main query, not your subquery.
 

jx3000

Ars Tribunus Militum
2,571
Thanks I'll give it a go.

One more question, did I do the following code segment correct

where (s.sno, r1.mark) in

(select r2.sno, r2.mark
from result r2

Can I use both sno and mark together like that.
An example was like that in my textbook, but the program I use seems to have problems with it. We use it at school only as a simple teaching tool, its called microsql, or msql.
 
Status
Not open for further replies.