sql server subqueries 2016

1

It is necessary to know the name of the students whose average grade of programming of the second year is higher than that of the program.

Here I enclose my query:

select nombre
from alumno innner join matricula on (alumno.#a=matricula.#a)
where (select avg(nota)
       from matricula inner join asignatura on (matricula.#asig=asignatura.#asig)
       where (nombre like 'bd') and (nota >(select avg(nota)
                                           from matricula inner join asignatura on (matricula.#asig=asignatura.#asig)
                                            where (nombre like 'programación'));

Structure of the database:

create table alumno(
  a smallint not null constraint PK_Alumno primary key,
  nombre varchar (50) not null
  );

create table profesor (
    p smallint not null constraint PK_Prof primary key,
    nombre varchar (50) not null);

create table asignatura (
     asig smallint not null constraint PK_ASIG primary key,
     nombre varchar (50) not null);

create table matrícula (
 asig smallint not null,
 a smallint not null,
  nota numeric (2,0) not null
  constraint Pk_MATR primary key (asig),
  constraint FK_MATR_AL foreign key (a) references alumno (a) on update cascade on delete cascade,
  constraint FK_MATR_AS foreign key (asig) references asignatura (asig) on update cascade on delete cascade);

  create table imparte(
    p smallint not null,
    asig smallint not null,
    curso varchar (30) not null,
    constraint PK_impart primary key (p,asig),
    constraint FK_IMPARTE_P foreign key (p) references profesor (p) on update cascade on delete cascade,
    constraint FK_IMPARTE_ASIG foreign key (asig) references asignatura (asig) on update cascade on delete cascade);
    
asked by ras212 14.06.2016 в 19:22
source

1 answer

1

If I have not understood you correctly, what you would try to do is:

SELECT alumno.nombre
FROM alumno
INNER JOIN matrícula ma ON ma.a=alumno.a
INNER JOIN asignatura aa ON aa.asig= ma.asig
WHERE aa.nombre = 'programación'
GROUP BY alumno.nombre, ma.asig
HAVING avg(ma.nota) > 
        (SELECT avg(mg.nota) FROM matrícula mg WHERE mg.asig = ma.asig)

Although seeing the definition of your tables, I understand that you should change the Primary Key of the license plate so that the main key is composed of the "asig" and "a" fields, and not only by asig.

    
answered by 14.06.2016 / 21:12
source