SQL example: What's the difference?
Posted in 1996
Topics: SQL Development & Query Writing, Triggers, Constraints & Referential Integrity
I run these two select statements that I think are equivalent but the results are
different!
What is wrong in 1?
1)
select p.numpieza, nompieza
from pieza p, preciosum ps
where p.numpieza=ps.numpieza
group by p.numpieza, nompieza
having avg(preciounit)>=all
(select max(preciocompra)
from linped
where linped.numpieza=p.numpieza)
2) This is the correct:
select p.numpieza, nompieza
from pieza p, preciosum ps
where p.numpieza=ps.numpieza
group by p.numpieza, nompieza
having avg(preciounit)>=
(select max(preciocompra)
from linped
where linped.numpieza=p.numpieza)
Output 1):
numpieza nompieza
DD-0001-210 DISCO DURO WESTERN DIG 210M 28
M-0001-C MONITOR SYNCMASTER 3 COLOR
M-0002-C MONITOR COLOR SONY BT
M-0003-C MONITOR IBM 3570 COLOR
P-0001-33 PLACA INTEL 33Mz
FD-0001-144 FLOPPY 1.44 IBM
FD-0002-720 FLOPPY 720K IBM
T-0001-IBM TECLADO XT IBM
T-0002-AT TECLADO AT SUSUSU
T-0003-AT TECLADO AT HP
O-0002-PP PACK PEGATINAS CONCIERTO JEVI
DD-0001-30 DISCO DURO 30M SEAGATE
Output 2):
numpieza nompieza (avg) (max)
DD-0001-210 DISCO DURO WESTERN DIG 210M 28 15333.33 15000
P-0001-33 PLACA INTEL 33Mz 25400.00 21000
T-0002-AT TECLADO AT SUSUSU 3116.67 3100
DK144-0002-P PACK DISKETTE 144 PANASONIC 555.00 545
O-0001-PP PEGATINAS CONCIERTO JEVI 1650.00 1500
C-400-Z FILTRO PANTALLA X200 775.00 700
and the DB schema:
create table "armando".vendedor
(
numvend smallint,
nomvend char(30),
nombrecomer char(30),
telefono char(15),
calle char(30),
ciudad char(20),
provincia char(20),
primary key (numvend)
);
create table "armando".pieza
(
numpieza char(16),
nompieza char(30),
preciovent integer,
primary key (numpieza)
);
create table "armando".pedido
(
numpedido smallint,
numvend smallint,
fecha date,
primary key (numpedido),
foreign key (numvend) references "armando".vendedor
);
create table "armando".preciosum
(
numpieza char(16),
numvend smallint,
preciounit integer,
diassum smallint,
descuento smallint,
primary key (numpieza,numvend),
foreign key (numpieza) references "armando".pieza,
foreign key (numvend) references "armando".vendedor
);
create table "armando".linped
(
numpedido smallint,
numlinea smallint,
numpieza char(16),
preciocompra integer,
cantpedida smallint,
fecharecep date,
cantrecibida smallint,
primary key (numpedido,numlinea),
foreign key (numpedido) references "armando".pedido
foreign key (numpieza) references "armando".pieza
);
Thanks a lot,
arMando
mailto:armando@dlsi.ua.es