Can you provide table structure and some sample data, and the output you expecting as sample below:-
DECLARE @students TABLE
( studentid int NOT NULL,
firstname varchar(max) not null,
lastname varchar(max) not null);
insert into @students
(studentid,firstname,lastname)
select … please define...
union all
select … please define...
DECLARE @results TABLE
( resultid int NOT NULL,
credits int not null);
insert into @results
(resultid,credits)
select … please define...
union all
select … please define...
DECLARE @courses TABLE
( courseid int NOT NULL,
credits int not null);
insert into @courses
(courseid,credits)
select … please define...
union all
select … please define...
I will help you once got above information. Just few line sample data and expecting result.
Which tables are dp, startyear and credits in? When you use multiple tables in a query, be sure to add the table alias prefix (s./r./c.) to all columns in the query. Especially when posting online, because we know nothing about your tables.
sorry... the dp, startyear are in the students table and the credits is in the courses. The tables link with studentid between the student and results table and then the courseid is found in the results and courses tables.
SELECT s.studentid,
MIN(s.firstname) AS firstname, MIN(s.lastname) AS lastname,
MIN(s.dp) AS dp, MIN(s.startyear) AS startyear,
ISNULL(SUM(c.credits), 0) AS totalcredits
FROM students s
LEFT OUTER JOIN results r ON s.studentid = r.studentid
LEFT OUTER JOIN courses c ON r.courseid = c.courseid
GROUP BY s.studentid
HAVING SUM(c.credits) IS NULL OR /*keep zero credits*/
SUM(c.credits) < ISNULL((
SELECT SUM(c.credits)
FROM students s
LEFT OUTER JOIN results r ON s.studentid = r.studentid
LEFT OUTER JOIN courses c ON r.courseid = c.courseid
WHERE s.studentid = 18), 9999999)