I made this code for SQL Server to select how many times the rider "AsdoVolante" came first in the first semester of 2017. But it does not work. What could be wrong?
SELECT P.Data, Nm.Nome, epp.PosicaoFinal
FROM Prova P, Piloto Nm, EquipaParticipaProva epp
WHERE epp.PosicaoFinal = (SELECT PosicaoFinal FROM EquipaParticipaProva where PosicaoFinal = 1)
HAVING Nm.Nome ='AsdoVolante' AND P.Data BETWEEN '2017-01-01' AND '2017-06-30';
Tables created in SQL Server for the code:
CREATE TABLE Carro(
IdCarro INT NOT NULL,
Marca VARCHAR(20) NOT NULL,
Modelo VARCHAR(50),
PRIMARY KEY (IdCarro));
CREATE TABLE Piloto(
IdPiloto INT NOT NULL,
Nome VARCHAR(20) NOT NULL,
Morada VARCHAR(50),
Telefone INT,
PRIMARY KEY (IdPiloto));
CREATE TABLE Equipa(
IdEquipa INT NOT NULL,
Nome VARCHAR(20),
Morada VARCHAR(50),
Telefone INT,
PRIMARY KEY (IdEquipa));
CREATE TABLE Patrocinador(
IdPatrocinador INT NOT NULL,
Nome VARCHAR(20)NOT NULL,
Morada VARCHAR(50),
PRIMARY KEY (IdPatrocinador));
CREATE TABLE Prova(
IdProva INT NOT NULL,
Nome VARCHAR(20) NOT NULL,
Local VARCHAR(50) NOT NULL,
Data DATE NOT NULL,
NrVoltas INT NOT NULL,
MelhorTempo TIME,
PRIMARY KEY (IdProva));
CREATE TABLE EquipaParticipaProva(
IdInscricao INT NOT NULL,
IdEquipa INT NOT NULL,
IdCarro INT NOT NULL,
IdPiloto INT NOT NULL,
IdProva INT NOT NULL,
PosicaoFinal INT,
TempoFinal TIME,
FOREIGN KEY (IdProva) REFERENCES Prova(IdProva),
FOREIGN KEY (IdCarro) REFERENCES Carro(IdCarro),
FOREIGN KEY (IdPiloto) REFERENCES Piloto(IdPiloto),
FOREIGN KEY (IdEquipa) REFERENCES Equipa(IdEquipa),
PRIMARY KEY (IdInscricao));
CREATE TABLE Voltas(
IdVolta INT NOT NULL,
IdInscricao INT NOT NULL,
PosicaoRelativa INT NOT NULL,
TempoVolta TIME,
FOREIGN KEY (IdInscricao) REFERENCES EquipaParticipaProva(IdInscricao),
PRIMARY KEY (IdVolta, IdInscricao));
CREATE TABLE PatrocinadorOficial(
IdPatrocinador INT NOT NULL,
IdProva INT NOT NULL,
Valor MONEY NOT NULL,
FOREIGN KEY (IdProva) REFERENCES Prova(IdProva),
PRIMARY KEY (IdPatrocinador, IdProva));
CREATE TABLE PatrocinadorNaoOficial(
IdPatrocinador INT NOT NULL,
IdProva INT NOT NULL,
Valor MONEY NOT NULL,
FOREIGN KEY (IdProva) REFERENCES Prova(IdProva),
PRIMARY KEY (IdPatrocinador, IdProva));
CREATE TABLE Mecanico(
IdMecanico INT NOT NULL,
Nome VARCHAR(20),
Morada VARCHAR(50),
Telefone INT,
PRIMARY KEY (IdMecanico));
CREATE TABLE Afinacao(
IdAfinacao INT NOT NULL,
IdMecanico INT NOT NULL,
IdEquipa INT NOT NULL,
TipoAfinacao VARCHAR(20) NOT NULL,
TempoDespendido TIME,
Data DATE NOT NULL,
FOREIGN KEY (IdEquipa) REFERENCES Equipa(IdEquipa),
FOREIGN KEY (IdMecanico) REFERENCES Mecanico(IdMecanico),
PRIMARY KEY (IdAfinacao));
Inserts created in SQL Server:
INSERT INTO Carro
VALUES (1, 'Nissan', 'Skyline');
INSERT INTO Carro
VALUES (2, 'Subaru', 'Impreza');
INSERT INTO Carro
VALUES (3, 'Mitsubishi', 'Evolution');
INSERT INTO Piloto
VALUES (111, 'Piloto 1', 'Castelo Branco', 111111111);
INSERT INTO Piloto
VALUES (112, 'Piloto 2', 'Castelo Branco', 111111112);
INSERT INTO Piloto
VALUES (113, 'JaGanhou', 'Lisboa', 111111113);
INSERT INTO Piloto
VALUES (114, 'AsdoVolante', 'Lisboa', 111111114);
INSERT INTO Piloto
VALUES (115, 'AsdoPedal', 'Beja', 111111115);
INSERT INTO Piloto
VALUES (116, 'Pelo Nome', 'Santarém', 111111116);
INSERT INTO Equipa
VALUES (001, 'OsAtolados', 'Castelo Branco', 272722123);
INSERT INTO Equipa
VALUES (002, 'Sparco', 'Lisboa', 212312432);
INSERT INTO Equipa
VALUES (003, 'ESTeam', 'Castelo Branco', 272343573);
INSERT INTO Prova
VALUES (010, 'RallycrossCB', 'Castelo Branco', '2017-02-02', 4, '00:04:20');
INSERT INTO Prova
VALUES (11, 'RallyLels', 'Bells', '2017-03-04', 10, '00:10:00');
INSERT INTO Prova
VALUES (12, 'Rally Portugal', 'Fafe', '2017-05-15', 2, '00:15:00');
INSERT INTO Prova
VALUES (13, 'Rally CB', 'Castelo Branco', '2017-01-01', 2, '00:15:00');
INSERT INTO Prova
VALUES (14, 'Rally Norte', 'Porto', '2017-02-02', 2, '00:30:00');
INSERT INTO EquipaParticipaProva
VALUES (441, 002, 3, 113, 010, 1, '00:04:00');
INSERT INTO EquipaParticipaProva
VALUES (442, 1, 2, 111, 11, 1, '00:10:00');
INSERT INTO EquipaParticipaProva
VALUES (443, 3, 1, 112, 10, 1,'00:05:00' );
INSERT INTO EquipaParticipaProva
VALUES (444, 3, 1, 114, 12, 1,'00:15:00' );
INSERT INTO EquipaParticipaProva
VALUES (445, 3, 1, 114, 13, 1,'00:15:00' );
INSERT INTO EquipaParticipaProva
VALUES (446, 3, 2, 114, 14, 5,'01:00:00' );
INSERT INTO Voltas
VALUES (1, 443, 1, '00:01:15');
INSERT INTO Voltas
VALUES (2, 443, 1, '00:01:15');
INSERT INTO Voltas
VALUES (3, 443, 3, '00:01:15');
INSERT INTO Voltas
VALUES (1, 444, 1, '00:07:30');
INSERT INTO Voltas
VALUES (2, 444, 1, '00:07:30');
INSERT INTO Voltas
VALUES (1, 445, 1, '00:07:30');
INSERT INTO Voltas
VALUES (2, 445, 1, '00:07:30');
INSERT INTO Voltas
VALUES (1, 446, 5, '00:30:00');
INSERT INTO Voltas
VALUES (2, 446, 5, '00:30:00');
INSERT INTO Voltas
VALUES (4, 443, 3, '00:01:15');
INSERT INTO Voltas
VALUES (1, 441, 1, '00:01:00' );
INSERT INTO Voltas
VALUES (2, 441, 1, '00:01:20');
INSERT INTO Voltas
VALUES (3, 441, 1, '00:01:00');
INSERT INTO Voltas
VALUES (4, 441, 1, '00:01:00');
INSERT INTO Voltas
VALUES (5, 441, 1, '00:01:00');
INSERT INTO Voltas
VALUES (6, 441, 1, '00:01:00');
INSERT INTO Voltas
VALUES (7, 441, 1, '00:01:00');
INSERT INTO Voltas
VALUES (8, 441, 1, '00:01:20');
INSERT INTO Voltas
VALUES (9, 441, 1 ,'00:00:30');
INSERT INTO Voltas
VALUES (10, 441, 1, '00:01:30');
INSERT INTO Voltas
VALUES (1, 441, 10, 2, '00:00:45');
INSERT INTO Voltas
VALUES (2, 441, 10, 2, '00:01:00');
INSERT INTO Voltas
VALUES (3, 441, 10, 2, '00:01:00');
INSERT INTO Voltas
VALUES (4, 441, 10, 2, '00:01:15');
INSERT INTO PATROCINADOR
VALUES(921, 'IPCB', 'Av da Talagueira');
INSERT INTO PATROCINADOR
VALUES(922, 'Bells Bar', 'Praceta Qualquer Coisa');
INSERT INTO PATROCINADOR
VALUES(923, 'MonsterEnergy', 'USA');
INSERT INTO PATROCINADOR
VALUES(924, 'Sical', 'Lisboa');
INSERT INTO PATROCINADOROFICIAL
VALUES(923, 010, 10000);
INSERT INTO PATROCINADOROFICIAL
VALUES(921, 11, 8000);
INSERT INTO PATROCINADORNAOOFICIAL
VALUES(920, 010, 5000);
INSERT INTO PATROCINADORNAOOFICIAL
VALUES(922, 11, 3000);
INSERT INTO PATROCINADORNAOOFICIAL
VALUES(924, 10, 6000);
INSERT INTO MECANICO
VALUES(333, 'Zacarias','Leiria',933628487);
INSERT INTO MECANICO
VALUES(334, 'Zé', 'Bragança', 963628487);
INSERT INTO MECANICO
VALUES(335, 'Luís', 'Lisboa', 913628487);
INSERT INTO AFINACAO
VALUES(20, 333, 001, 'Travões', '1:00:00', '2017-02-03');
INSERT INTO AFINACAO
VALUES(21, 334, 002, 'Luzes', '00:15:00', '2017-02-03');
INSERT INTO AFINACAO
VALUES(22, 335, 003, 'Travoes', '1:00:00', '2017-02-01');
try this
SELECT P.Data, Nm.Nome, epp.PosicaoFinal
FROM Prova P, Piloto Nm, EquipaParticipaProva epp
WHERE epp.PosicaoFinal **IN** (SELECT PosicaoFinal FROM EquipaParticipaProva where PosicaoFinal = 1)
HAVING Nm.Nome ='AsdoVolante' AND P.Data BETWEEN '2017-01-01' AND '2017-06-30';
It will work for you
Related
I need my SQL db to be able to hold more than one reservation for a customer.
However I get some duplicate pk errors.
Here is my SQL script: (I wanna be able to let one customer have more than 1 reserv.)
/*
db_name: Restaurant DB
update_timestamp: 6.10.2021 # 09:48
sign: The Actual Daniel
*/
DROP DATABASE IF EXISTS restaurantDB;
CREATE DATABASE restaurantDB;
USE restaurantDB;
CREATE TABLE `bill` (
`billID` int NOT NULL AUTO_INCREMENT,
`payAmount` varchar(255) NOT NULL,
PRIMARY KEY (`billID`)
);
INSERT INTO `bill` VALUES (1, '$258');
INSERT INTO `bill` VALUES (2, '$420');
INSERT INTO `bill` VALUES (3, '$114');
INSERT INTO `bill` VALUES (4, '$88');
INSERT INTO `bill` VALUES (5, '$137');
INSERT INTO `bill` VALUES (6, '$286');
INSERT INTO `bill` VALUES (7, '$97');
INSERT INTO `bill` VALUES (8, '$110');
INSERT INTO `bill` VALUES (9, '$358');
INSERT INTO `bill` VALUES (10, '$190');
CREATE TABLE `customer` (
`customerID` int NOT NULL AUTO_INCREMENT,
`firstName` varchar(255) NOT NULL,
`lastName` varchar(255) NOT NULL,
`phone` varchar(20) NOT NULL,
PRIMARY KEY (`customerID`)
);
INSERT INTO `customer` VALUES (1, 'Nero', 'Lee', '420420589');
INSERT INTO `customer` VALUES (2, 'Lucius', 'Malt', '578632221');
INSERT INTO `customer` VALUES (3, 'Aurelian', 'Keen', '639456773');
INSERT INTO `customer` VALUES (4, 'Jasmine', 'Wang', '227453891');
INSERT INTO `customer` VALUES (5, 'Sophie', 'Clinck', '905674321');
INSERT INTO `customer` VALUES (6, 'Augustus', 'Smith', '523764112');
INSERT INTO `customer` VALUES (7, 'Isabelle', 'Niaom', '786554330');
INSERT INTO `customer` VALUES (8, 'Alix', 'Black', '009886775');
INSERT INTO `customer` VALUES (9, 'Leia', 'Mudworth', '345667228');
INSERT INTO `customer` VALUES (10, 'Claudius', 'Reed', '427654221');
CREATE TABLE `meal` (
`mealID` int NOT NULL AUTO_INCREMENT,
`sides` varchar(255) NULL,
`main` varchar(255) NULL,
`beverage` varchar(255) NOT NULL,
PRIMARY KEY (`mealID`)
);
INSERT INTO `meal` VALUES (1, 'potatos', 'steak', 'wine');
INSERT INTO `meal` VALUES (2, 'ice', 'cube steak', 'spring water');
INSERT INTO `meal` VALUES (3, 'rice', 'cake', 'beer');
INSERT INTO `meal` VALUES (4, 'salad', 'pasta', 'wine');
INSERT INTO `meal` VALUES (5, 'radish', 'noodles', 'soju');
INSERT INTO `meal` VALUES (6, 'rice', 'rice', 'pumpkin juice');
INSERT INTO `meal` VALUES (7, 'butter, honey', 'steak', 'wine');
INSERT INTO `meal` VALUES (8, 'ice', 'salad', 'mineral water');
INSERT INTO `meal` VALUES (9, 'sweet potatos', 'pork', 'beer');
INSERT INTO `meal` VALUES (10, 'sourdough bread', 'fruit bowl', 'mineral water');
CREATE TABLE `order` (
`orderID` int NOT NULL,
`time` datetime NOT NULL,
PRIMARY KEY (`orderID`)
);
INSERT INTO `order` VALUES (1, '21-09-27 13:36:06');
INSERT INTO `order` VALUES (2, '21-02-14 17:18:03');
INSERT INTO `order` VALUES (3, '21-03-27 11:34:16');
INSERT INTO `order` VALUES (4, '21-07-14 15:58:32');
INSERT INTO `order` VALUES (5, '21-02-27 18:16:33');
INSERT INTO `order` VALUES (6, '21-01-14 19:28:12');
INSERT INTO `order` VALUES (7, '21-08-27 16:27:07');
INSERT INTO `order` VALUES (8, '21-06-14 11:21:09');
INSERT INTO `order` VALUES (9, '21-11-27 16:30:03');
INSERT INTO `order` VALUES (10, '21-03-14 17:22:11');
CREATE TABLE `reservation` (
`reservationID` int NOT NULL AUTO_INCREMENT,
`checkIn` datetime NOT NULL,
`checkOut` datetime NOT NULL,
`customerForeign` int NOT NULL,
PRIMARY KEY (`reservationID`),
FOREIGN KEY (`customerForeign`) REFERENCES customer(customerID)
);
INSERT INTO `reservation` VALUES (1, '21-09-27 13:24:06', '21-09-27 14:17:23', 1);
INSERT INTO `reservation` VALUES (2, '21-02-14 17:25:03', '21-02-14 19:22:14', 2);
INSERT INTO `reservation` VALUES (3, '21-03-27 11:34:16', '21-03-27 13:34:16', 3);
INSERT INTO `reservation` VALUES (4, '21-07-14 15:58:32', '21-07-14 16:58:32', 4);
INSERT INTO `reservation` VALUES (5, '21-02-27 18:16:33', '21-02-27 19:16:33', 5);
INSERT INTO `reservation` VALUES (6, '21-01-14 19:28:12', '21-01-14 20:28:12', 6);
INSERT INTO `reservation` VALUES (7, '21-08-27 16:27:07', '21-08-27 17:27:07', 7);
INSERT INTO `reservation` VALUES (8, '21-06-14 11:21:09', '21-06-14 14:21:09', 8);
INSERT INTO `reservation` VALUES (9, '21-11-27 16:30:03', '21-11-27 17:30:03', 9);
INSERT INTO `reservation` VALUES (10, '21-03-14 17:22:11', '21-03-14 19:22:11', 10);
CREATE TABLE `table` (
`tableID` int NOT NULL,
`numOfSeats` int NOT NULL,
PRIMARY KEY (`tableID`)
);
INSERT INTO `table` VALUES (1, 1);
INSERT INTO `table` VALUES (2, 2);
INSERT INTO `table` VALUES (3, 2);
INSERT INTO `table` VALUES (4, 2);
INSERT INTO `table` VALUES (5, 4);
INSERT INTO `table` VALUES (6, 4);
INSERT INTO `table` VALUES (7, 6);
INSERT INTO `table` VALUES (8, 6);
INSERT INTO `table` VALUES (9, 8);
INSERT INTO `table` VALUES (10, 12);
ALTER TABLE `bill` ADD CONSTRAINT `fk_bill_order_1` FOREIGN KEY (`billID`) REFERENCES `order` (`orderID`);
ALTER TABLE `meal` ADD CONSTRAINT `fk_meal_order_1` FOREIGN KEY (`mealID`) REFERENCES `order` (`orderID`);
ALTER TABLE `order` ADD CONSTRAINT `fk_order_customer_1` FOREIGN KEY (`orderID`) REFERENCES `customer` (`customerID`);
ALTER TABLE `reservation` ADD CONSTRAINT `fk_reservation_customer_1` FOREIGN KEY (`reservationID`) REFERENCES `customer` (`customerID`);
ALTER TABLE `table` ADD CONSTRAINT `fk_table_reservation_1` FOREIGN KEY (`tableID`) REFERENCES `reservation` (`reservationID`);
This is error I get when trying to insert new reservation for customer with ID of 1
I need to make sure that the query listed below is implemented as a nested query with EXISTS/NOT EXISTS clauses.
"Find the first and last name of drivers who performed at least one trip in 2017."
Here is my code so far:
SELECT EMPLOYEE.FNAME, EMPLOYEE.LNAME
FROM EMPLOYEE
WHERE EXISTS
(SELECT ENUM FROM DRIVER WHERE EMPLOYEE.ENUM=DRIVER.ENUM) AND
(SELECT LNUM FROM TRIP WHERE TRIP.LNUM=DRIVER.LNUM AND
YEAR(TDATE)=2017);
I am not sure whether or not it is a syntax error or whether I have entered the wrong values. However, I triple checked all the values and they seem to match the table data.
Below I have listed the tables:
CREATE TABLE TRIP(
TNUM DECIMAL(10) NOT NULL,
LNUM DECIMAL(8) NOT NULL,
REGNUM VARCHAR(10) NOT NULL,
TDATE DATE NOT NULL,
CONSTRAINT TRIP_PKEY PRIMARY KEY (TNUM),
CONSTRAINT TRIP_CKEY UNIQUE (LNUM, REGNUM, TDATE),
CONSTRAINT TRIP_FKEY1 FOREIGN KEY (LNUM) REFERENCES DRIVER(LNUM),
CONSTRAINT TRIP_FKEY2 FOREIGN KEY (REGNUM) REFERENCES TRUCK(REGNUM) );
CREATE TABLE DRIVER(
ENUM DECIMAL(12) NOT NULL,
LNUM DECIMAL(8) NOT NULL,
STATUS VARCHAR(10) NOT NULL,
CONSTRAINT DRIVER_PKEY PRIMARY KEY(ENUM),
CONSTRAINT DRIVER_UNIQUE UNIQUE(LNUM),
CONSTRAINT DRIVER_FKEY FOREIGN KEY(ENUM) REFERENCES EMPLOYEE(ENUM),
CONSTRAINT DRIVER_STATUS CHECK ( STATUS IN ('AVAILABLE', 'BUSY', 'ON
LEAVE')) );
CREATE TABLE EMPLOYEE(
ENUM DECIMAL(12) NOT NULL,
FNAME VARCHAR(50) NOT NULL,
INITIALS VARCHAR(5) NULL,
LNAME VARCHAR(50) NOT NULL,
DOB DATE NULL,
BLDG DECIMAL(3) NOT NULL,
STREET VARCHAR(50) NOT NULL,
SUBURB VARCHAR(50) NOT NULL,
STATE VARCHAR(5) NOT NULL,
ZIPCODE DECIMAL(4) NOT NULL,
CONSTRAINT EMPLOYEE_PKEY PRIMARY KEY(ENUM) );
Below I have listed the table data:
INSERT INTO TRIP VALUES( 1, 10001, 'PKR768', '2015-01-12' );
INSERT INTO TRIP VALUES( 2, 10001, 'SYF777', '2015-02-20' );
INSERT INTO TRIP VALUES( 3, 10001, 'KKK007', '2015-03-12' );
INSERT INTO TRIP VALUES( 4, 10001, 'PKR768', '2015-06-29' );
INSERT INTO TRIP VALUES( 5, 20002, 'PKR768', '2015-01-12' );
INSERT INTO TRIP VALUES( 6, 10002, 'SYF777', '2015-02-20' );
INSERT INTO TRIP VALUES( 7, 30005, 'KKK007', '2015-03-12' );
INSERT INTO TRIP VALUES( 8, 10001, 'PKR768', '2015-01-13' );
INSERT INTO TRIP VALUES( 9, 10002, 'QRT834', '2015-09-17' );
INSERT INTO TRIP VALUES(10, 30005, 'KKK007', '2015-12-15' );
INSERT INTO TRIP VALUES(11, 10003, 'SST005', '2016-01-23' );
INSERT INTO TRIP VALUES(12, 10002, 'PKR768', '2016-03-12' );
INSERT INTO TRIP VALUES(13, 20002, 'QRT834', '2015-04-23' );
INSERT INTO TRIP VALUES(14, 20002, 'PKR008', '2015-04-23' );
INSERT INTO TRIP VALUES(15, 30005, 'PKR768', '2015-05-24' );
INSERT INTO TRIP VALUES(16, 30005, 'SST005', '2014-08-02' );
INSERT INTO TRIP VALUES(17, 20002, 'QRT834', '2014-09-17' );
INSERT INTO TRIP VALUES(18, 10001, 'KKK007', '2014-12-15' );
INSERT INTO TRIP VALUES(19, 30005, 'SST005', '2016-01-23' );
INSERT INTO TRIP VALUES(20, 10003, 'PKR768', '2016-03-12' );
INSERT INTO TRIP VALUES(21, 10001, 'QRT834', '2012-04-23' );
INSERT INTO TRIP VALUES(22, 30005, 'PKR008', '2012-04-23' );
INSERT INTO TRIP VALUES(23, 10003, 'PKR768', '2012-05-25' );
INSERT INTO TRIP VALUES(24, 20002, 'SST005', '2012-08-02' );
INSERT INTO TRIP VALUES(25, 10001, 'PKR768', '2014-01-12' );
INSERT INTO TRIP VALUES(26, 10001, 'SYF777', '2013-02-20' );
INSERT INTO TRIP VALUES(27, 20002, 'KKK007', '2013-03-12' );
INSERT INTO TRIP VALUES(28, 30005, 'PKR768', '2010-06-29' );
INSERT INTO TRIP VALUES(29, 10001, 'QRT834', '2010-09-17' );
INSERT INTO TRIP VALUES(30, 10002, 'KKK007', '2010-12-15' );
INSERT INTO TRIP VALUES(31, 10003, 'SST005', '2010-01-23' );
INSERT INTO TRIP VALUES(32, 20002, 'PKR768', '2010-03-12' );
INSERT INTO TRIP VALUES(33, 30005, 'QRT834', '2003-04-23' );
INSERT INTO TRIP VALUES(34, 30005, 'PKR008', '2004-04-23' );
INSERT INTO TRIP VALUES(35, 10001, 'PKR768', '2017-05-24' );
INSERT INTO DRIVER VALUES( 1, 10001, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 2, 10008, 'ON LEAVE' );
INSERT INTO DRIVER VALUES( 3, 10002, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 4, 10004, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 5, 10003, 'ON LEAVE' );
INSERT INTO DRIVER VALUES( 6, 10012, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 7, 20002, 'BUSY' );
INSERT INTO DRIVER VALUES( 8, 20003, 'BUSY' );
INSERT INTO DRIVER VALUES( 9, 30005, 'BUSY' );
INSERT INTO DRIVER VALUES( 10, 40002, 'BUSY' );
INSERT INTO DRIVER VALUES( 11, 20045, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 12, 20055, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 13, 20065, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 14, 10305, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 15, 10345, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 16, 10705, 'AVAILABLE' );
INSERT INTO DRIVER VALUES( 17, 40005, 'AVAILABLE' );
INSERT INTO EMPLOYEE VALUES( 1, 'John', NULL, 'Smith', NULL, 42,
'Victoria St.', 'Hurstville', 'NSW', 2456 );
INSERT INTO EMPLOYEE VALUES( 2, 'Peter', NULL, 'Taylor', '1970-01-
12', 42, 'Victoria St.', 'Hurstville', 'NSW', 2456 );
INSERT INTO EMPLOYEE VALUES( 3, 'John', NULL, 'Doe', '1966-03-23',
12, 'Station St.', 'Dapto', 'NSW', 2530 );
INSERT INTO EMPLOYEE VALUES( 4, 'John', NULL, 'Gray', '1988-05-05',
16, 'Station St.', 'Dapto', 'NSW', 2530 );
INSERT INTO EMPLOYEE VALUES( 5, 'Adam', NULL, 'Taylor', '1980-01-01',
42, 'Church St.', 'City', 'NSW', 2300 );
INSERT INTO EMPLOYEE VALUES( 6, 'Michael', NULL, 'Jones', '1975-03-
05', 23, 'Waterloo Ave.', 'Surry Hills', 'NSW', 2502 );
INSERT INTO EMPLOYEE VALUES( 7, 'Frederic', NULL, 'Jones', NULL, 3,
'Victoria St.', 'Redfern', 'NSW', 2420 );
INSERT INTO EMPLOYEE VALUES( 8, 'Peter', NULL, 'O''Brien', '1983-02-
28', 19, 'Lucas Dr.', 'Horsley', 'NSW', 2530 );
INSERT INTO EMPLOYEE VALUES( 9, 'John', NULL, 'Lucas', '1966-12-16',
20, 'Huxley St.', 'Horsley', 'NSW', 2530 );
INSERT INTO EMPLOYEE VALUES( 10, 'John', NULL, 'Fox', '1975-10-15',
18, 'Victoria St.', 'Hurstville', 'NSW', 2456 );
INSERT INTO EMPLOYEE VALUES( 11, 'Adam', NULL, 'Fox', NULL, 45,
'Victoria St.', 'Hurstville', 'NSW', 2456 );
INSERT INTO EMPLOYEE VALUES( 12, 'Phillip', NULL, ',Cox', '1984-12-
12', 5, 'The Avenue', 'Rockdale', 'NSW', 2300 );
INSERT INTO EMPLOYEE VALUES( 13, 'Andrew', 'K', 'Smith', '1969-04-
04', 42, 'Bambaramba Ave.', 'Pennant Hills', 'NSW', 2556 );
INSERT INTO EMPLOYEE VALUES( 14, 'Andrew', 'R', 'Smith', '1992-04-
01', 67, 'King Cr.', 'Hurstville', 'NSW', 2456 );
INSERT INTO EMPLOYEE VALUES( 15, 'Michael', NULL, 'Potter', '1995-04-
01', 568, 'Bong Bong St.', 'Horsley', 'NSW', 2530 );
INSERT INTO EMPLOYEE VALUES( 16, 'Harry', NULL, 'Potter', '1995-04-
01', 568, 'Bong Bong St.', 'Horsley', 'NSW', 2530 );
INSERT INTO EMPLOYEE VALUES( 17, 'James', NULL, 'Bond', NULL, 007,
'Alan Bond St.', 'Perth', 'WA', 6000 );
INSERT INTO EMPLOYEE VALUES( 18, 'Paris', NULL, 'Hilton', NULL, 1,
'Hilton St.', 'Melbourne', 'Vic', 3000 );
INSERT INTO EMPLOYEE VALUES( 19, 'Lady', NULL, 'Gaga', NULL, 3, 'Pork
st.', 'Hobart', 'Tas', 7000 );
INSERT INTO EMPLOYEE VALUES( 20, 'Robin', NULL, 'Hood', NULL, 6,
'Nottingham Pl.', 'Sydney', 'NSW', 2000 );
The correct syntax is:
SELECT E.FNAME, E.LNAME
FROM EMPLOYEE E
WHERE EXISTS (SELECT 1
FROM DRIVER D
WHERE D.ENUM = E.ENUM
) AND
EXISTS (SELECT 1
FROM TRIP T
WHERE T.LNUM = E.LNUM AND YEAR(T.TDATE) = 2017
);
You need to repeat the EXISTS. In addition:
Use table aliases and qualify all column references. This is a best practice, so get used to it now when you are learning SQL.
The value in the SELECT for an EXISTS is irrelevant. I use 1 because it is easy to type.
Not all databases support YEAR(). The standard syntax is EXTRACT(YEAR FROM T.TDATE). I assume your database does support the function you are using.
I doubt that you really need to compare to DRIVERS (in the real world). Wouldn't a drive on a trip automatically be a "driver"?
I have to prepare and execute a script file to create and populate a relational database in Oracle with data about customers, current orders, and products. These are the relationships: Each customer can place any number of current orders and each current order is placed by one customer.Each current order is for one product but each product can be in any number of
current orders.
I can't figure out the errors when running this script. The Customer and Products table are successfully filled, but the Current_Orders table is not. There are a few error codes that appear when I run it but I am not understanding them as I am fairly new to SQL. Any help would be appreciated. Thanks! ORA-00001, ORA-00955, ORA-02449.
drop table Customer;
drop table Current_Orders;
drop table Products;
create table Customer
(Customer_Number integer not null,
Customer_Name char(20) not null,
Customer_City char(20) not null,
PRIMARY KEY(Customer_Number));
create table Products
(Product_Number integer not null,
Product_Description char(20) not null,
Unit_Price integer not null,
PRIMARY KEY (Product_Number));
create table Current_Orders
(Order_Number integer not null,
Order_Date date not null,
Shipping_Method char(20) not null,
Product_Number integer not null,
Quantity_Ordered integer not null,
Customer_Number integer not null,
PRIMARY KEY(Order_Number), FOREIGN KEY(Customer_Number)
references Customer(Customer_Number) ON DELETE CASCADE,
FOREIGN KEY(Product_Number) references Products(Product_Number)
ON DELETE CASCADE);
insert into Customer
values (1, 'Khizur Sheikh', 'Milpitas');
insert into Customer
values (2, 'Fatima Sheikh', 'Fremont');
insert into Customer
values (3, 'Syed Sheikh', 'Davis');
insert into Customer
values (4, 'Mohammed Sheikh', 'Oakland');
insert into Customer
values (5, 'Ali Sheikh', 'Dublin');
insert into Products
values (6, 'iphone', 300);
insert into Products
values (7, 'ipad', 400);
insert into Products
values (8, 'imac', 500);
insert into Products
values (9, 'ipod', 600);
insert into Products
values (10, 'ihome', 700);
insert into Products
values (11, 'apple', 800);
insert into Products
values (12, 'banana', 900);
insert into Products
values (13, 'orange', 1000);
insert into Products
values (14, 'grape', 1100);
insert into Products
values (15, 'avocado', 1200);
insert into Products
values (16, 'bread', 1300);
insert into Products
values (17, 'muffin', 1400);
insert into Products
values (18, 'cheese', 1500);
insert into Products
values (19, 'milk', 1600);
insert into Products
values (20, 'brownies', 1700);
insert into Products
values (21, 'candy', 1800);
insert into Products
values (22, 'soup', 1900);
insert into Products
values (23, 'strawberry', 11000);
insert into Products
values (24, 'cookies', 50);
insert into Products
values (25, 'chocolate', 10);
insert into Current_Orders
values (26, '22-oct-2017', 'truck', 6, 1, 1);
insert into Current_Orders
values (27, '22-nov-2017', 'ship', 7, 1, 2);
insert into Current_Orders
values (28, '22-dec-2017', 'train', 8, 3, 3);
insert into Current_Orders
values (29, '22-jan-2017', 'truck', 9, 2, 4);
insert into Current_Orders
values (30, '22-feb-2017', 'train', 10, 1, 5);
insert into Current_Orders
values (31, '22-mar-2017', 'truck', 12, 4, 2);
insert into Current_Orders
values (32, '22-apr-2017', 'plane', 17, 7, 4);
insert into Current_Orders
values (33, '22-may-2017', 'train', 19, 1, 5);
insert into Current_Orders
values (34, '22-jun-2017', 'ship', 22, 3, 2);
insert into Current_Orders
values (35, '22-jan-2017', 'ship', 21, 4, 3);
commit;
All the commands in your script work fine while running for the first time. However Issue seems to occur when you run the DROP TABLE statements on second and successive executions when table exists and has data.
drop table Customer;
drop table Current_Orders;
Error report - ORA-02449: unique/primary keys in table referenced by
foreign keys
02449. 00000 - "unique/primary keys in table referenced by foreign keys"
*Cause: An attempt was made to drop a table with unique or
primary keys referenced by foreign keys in another table.
*Action: Before performing the above operations the table, drop the
foreign key constraints in other tables.
I see you have defined a FOREIGN KEY on the column Customer_Number
FOREIGN KEY(Customer_Number)
references Customer(Customer_Number) ON DELETE CASCADE
So, when you try to DROP from Table Customer before Current_Orders , you are basically deleting parent record before deleting the child record which is not allowed. ORA-00955 and ORA-00001 occur as a consequence.
So, follow this order to drop tables in your script.
drop table Current_Orders;
drop table Products;
drop table Customer;
Table Schema:
CREATE TABLE [dbo].[VMaster](
[VID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[VName] [varchar](30) NOT NULL
)
GO
CREATE TABLE [dbo].[TblMaster](
[SID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[VID] [int] NOT NULL,
[CreatedDate] [datetime] default (getdate()) NOT NULL,
[CharToAdd] [varchar](10) NOT NULL,
[Start] [int] NOT NULL,
[End] [int] NOT NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[TblDetails](
[DetailsID] [int] IDENTITY(1,1) NOT NULL Primary Key,
[SID] [int] NOT NULL,
[Sno] [int] NOT NULL,
[ConcatenatedText] [varchar](20) NOT NULL,
[isIssued] [bit] default (0) NOT NULL,
[isUsed] [bit] default (0) NOT NULL
)
GO
ALTER TABLE [dbo].[TblMaster] WITH CHECK ADD CONSTRAINT [fk_SI_id] FOREIGN KEY([VID])
REFERENCES [dbo].[VMaster] ([VID])
GO
ALTER TABLE [dbo].[TblMaster] CHECK CONSTRAINT [fk_SI_id]
GO
Sample data:
Insert into dbo.VMaster Values ('A1')
Insert into dbo.VMaster Values ('A2')
GO
Insert into dbo.TblMaster Values (1,default, 'ABC', 1, 5)
Insert into dbo.TblMaster Values (1,default, 'XYZ', 10, 20)
Insert into dbo.TblMaster Values (2,default, 'P1', 10, 15)
GO
Insert into dbo.TblDetails values(1, 1, 'ABC1', 1,0)
Insert into dbo.TblDetails values(1, 2, 'ABC2', 1,0)
Insert into dbo.TblDetails values(1, 3, 'ABC3', 1,0)
Insert into dbo.TblDetails values(1, 4, 'ABC4', 0,0)
Insert into dbo.TblDetails values(1, 5, 'ABC5', 0,0)
Insert into dbo.TblDetails values(2, 10, 'XYZ10', 1,0)
Insert into dbo.TblDetails values(2, 11, 'XYZ11', 1,0)
Insert into dbo.TblDetails values(2, 12, 'XYZ12', 1,0)
Insert into dbo.TblDetails values(2, 13, 'XYZ13', 1,0)
Insert into dbo.TblDetails values(2, 14, 'XYZ14', 1,0)
Insert into dbo.TblDetails values(2, 15, 'XYZ15', 0,0)
Insert into dbo.TblDetails values(2, 16, 'XYZ16', 0,0)
Insert into dbo.TblDetails values(2, 17, 'XYZ17', 0,0)
Insert into dbo.TblDetails values(2, 18, 'XYZ18', 0,0)
Insert into dbo.TblDetails values(2, 19, 'XYZ19', 0,0)
Insert into dbo.TblDetails values(2, 20, 'XYZ20', 0,0)
Insert into dbo.TblDetails values(3, 10, 'P110', 1,0)
Insert into dbo.TblDetails values(3, 11, 'P111', 1,0)
Insert into dbo.TblDetails values(3, 12, 'P112', 1,0)
Insert into dbo.TblDetails values(3, 13, 'P113', 1,0)
Insert into dbo.TblDetails values(3, 14, 'P114', 1,0)
Insert into dbo.TblDetails values(3, 15, 'P115', 1,0)
GO
Expected Output:
Query which I have as of now:
SELECT
TM.VID, VM.VName, TM.CharToAdd, TM.Start, TM.[End],
(SELECT COUNT(*) FROM dbo.TblDetails TD where TD.SID=TM.SID and isIssued = 0 ) Balance
FROM
dbo.TblMaster TM, dbo.VMaster VM
Where VM.VID = TM.VID
I am trying to calculate total matching records in TblDetails for each VID whose isIssued value is 0.
User could select a period (date range) for which they want to see this output. For that TblMaster.CreatedDate is what we have to use.
Also user can select a specific VID and like to see the result only for that.
Just in case if date range or VID is not provided then this has to work against the whole table! Per month there might be 500000 records in TblDetails and we will hold 12 months of data.
For the summary of the whole table your query looks OK.
It is easy to add an optional filtering on top of that.
If parameter is NULL, it will be ignored. If parameter is not NULL, it will limit the result set:
DECLARE #ParamStart datetime = '2016-01-01';
DECLARE #ParamEnd datetime = '2017-01-01';
DECLARE #ParamVID int = NULL;
SELECT
TM.VID, VM.VName, TM.CharToAdd, TM.Start, TM.[End],
(SELECT COUNT(*) FROM dbo.TblDetails TD where TD.SID=TM.SID and isIssued = 0) Balance
FROM
dbo.TblMaster AS TM
INNER JOIN dbo.VMaster AS VM ON VM.VID = TM.VID
WHERE
(TM.CreatedDate >= #ParamStart OR #ParamStart IS NULL)
AND (TM.CreatedDate < #ParamEnd OR #ParamEnd IS NULL)
AND (TM.VID = #ParamVID OR #ParamVID IS NULL)
ORDER BY TM.SID
OPTION(RECOMPILE);
To make it efficient, it should help to have this index:
CREATE NONCLUSTERED INDEX [IX_] ON [dbo].[TblDetails]
(
[isIssued] ASC,
[SID] ASC
)
And also indexes on dbo.TblMaster.CreatedDate and dbo.TblMaster.VID.
I have this Data in DB
CREATE TABLE Stu_Table
(
Stu_Id VARCHAR(2),
Stu_Name VARCHAR(15),
Stu_Class VARCHAR(10),
sub_id VARCHAR(2),
marks VARCHAR(3)
);
INSERT INTO Stu_Table VALUES (1, 'Komal', 10, 1, 45);
INSERT INTO Stu_Table VALUES (2, 'Ajay', 10, 1, 56);
INSERT INTO Stu_Table VALUES (3, 'Rakesh', 10, 1, 67);
INSERT INTO Stu_Table VALUES (1, 'Komal', 10, 2, 47);
INSERT INTO Stu_Table VALUES (2, 'Ajay', 10, 2, 53);
INSERT INTO Stu_Table VALUES (3, 'Rakesh', 10, 2, 57);
INSERT INTO Stu_Table VALUES (1, 'Komal', 10, 3, 45);
INSERT INTO Stu_Table VALUES (2, 'Ajay', 10, 3, 56);
INSERT INTO Stu_Table VALUES (3, 'Rakesh', 10, 3, 67);
INSERT INTO Stu_Table VALUES (1, 'Komal', 10, 4, 65);
INSERT INTO Stu_Table VALUES (2, 'Ajay', 10, 4, 56);
INSERT INTO Stu_Table VALUES (3, 'Rakesh', 10, 4, 37);
INSERT INTO Stu_Table VALUES (1, 'Komal', 10, 5, 65);
INSERT INTO Stu_Table VALUES (2, 'Ajay', 10, 5, 46);
INSERT INTO Stu_Table VALUES (3, 'Rakesh', 10, 5, 63);
And I'm doing this query on this data.
SELECT *
FROM
(
SELECT
Stu_Id,
MIN(marks) AS mini,
AVG(marks) AS per
FROM stu_table
GROUP BY stu_id
HAVING MIN(marks) > 45
);
And I'm getting this:
Stu_Id| mini | per
1 | 45 | 53.4
2 | 46 | 53.4
3 | 37 | 58.2
I don't understand why I still see Stu_Id 1 with min(mark)=45 when I clearly have this HAVING min(marks)>45 in my query.
Runnable Demo
FIX:
Thanks to #sybkar and #Martin Smith!
I set the marks type as a string.
It's should be INT...
Thanks guys!
Working perfect!
create table Stu_Table(Stu_Id INT(2), Stu_Name varchar(15),
Stu_Class varchar(10),sub_id INT(2),marks INT(3));<--INT!!!
I don't understand why I still see Stu_Id 1 with min(mark)=45
when I clearly have this HAVING min(marks)>45 in my query.
You don't. Or at the least the demo you have provided doesn't.
In general any weird results that you are getting will be because marks is being stored as a string so MIN(marks) will be bringing back the earliest in alphabetical order though.
For example HAVING MIN(marks) > 45 will also bring back 5, 6, 7, 8 and 9