Create trigger ORACLE - sql

I have to create a trigger that records order numbers in the purchase table. PURCHASE the training database and audit information into the AUDIT_TAB table. This is a task from the book Christopher Allen How to write powerful and flexible programs on PL / SQL.
CREATE TABLE audit
(ORDER_NUMBER NUMBER(10),
person_code VARCHAR2(3),
user_name CHAR(30),
user_machine CHAR(20),
change_in_quant NUMBER(5),
transaction_time DATE,
FOREIGN KEY (person_code) REFERENCES persoon);
CREATE SEQUENCE order_num_seq;
CREATE OR REPLACE TRIGGER audit_trigger
BEFORE INSERT OR UPDATE ON purchase
FOR EACH ROW
DECLARE
no_name_change EXCEPTION;
quant_change NUMBER(5) := 0;
BEGIN
IF (UPDATING
AND
(:NEW.product_name <> :OLD.product_name))
THEN
RAISE no_name_change;
END IF;
IF (((UPDATING)
AND
(:OLD.ORDER_NUMBER IS NULL))
OR
((INSERTING)
AND
(:NEW.ORDER_NUMBER IS NULL)))
THEN
SELECT order_num_seq.NEXTVAL
INTO :NEW.ORDER_NUMBER
FROM dual;
END IF;
IF (UPDATING)
THEN
quant_change := :NEW. quantity - :OLD. quantity;
ELSE
quant_change := :NEW. quantity;
END IF;
INSERT INTO audit
VALUES ( :NEW.ORDER_NUMBER,
:NEW.salesperson,
USER,
USERENV ( 'TERMINAL' ) ,
quant_change,
SYSDATE) ;
EXCEPTION
WHEN no_name_change
THEN
dbms_output.put_line ('Change of product name not allowed');
dbms_output.put_line ('Aborting and resetting to old values');
:NEW.product_name := :OLD.product_name;
:NEW. salesperson := :OLD.salesperson;
:NEW.ORDER_NUMBER := :OLD.ORDER_NUMBER;
:NEW. quantity := :OLD.quantity;
END audit_trigger ;
/
And trigger compiled with warnings. Why? What's my mistake?
My database:
CREATE TABLE person (
person_code VARCHAR2(3) PRIMARY KEY,
first_name VARCHAR2(15),
last_name VARCHAR2(20),
hire_date DATE
);
CREATE INDEX person_name_index
ON person(last_name, first_name);
ALTER TABLE person
ADD CONSTRAINT person_unique UNIQUE (
first_name,
last_name,
hire_date
);
INSERT INTO person VALUES
('CA', 'Charlene', 'Atlas', '01-ФЕВ-02');
INSERT INTO person VALUES
('GA', 'Gary', 'Andersen', '15-ФЕВ-02' );
INSERT INTO person VALUES
('BB', 'Bobby', 'Barkenhagen', '28-ФЕВ-02');
INSERT INTO person VALUES
('LB', 'Laren', 'Baxter', '01-МАР-02 ');
INSERT INTO person VALUES
('LN', 'Linda', 'Norton', '01-ИЮН-03');
CREATE TABLE product (
product_name VARCHAR2(25) PRIMARY KEY,
product_price NUMBER(4,2),
quantity_on_hand NUMBER(5,0),
last_stock_date DATE
);
ALTER TABLE product ADD (
CONSTRAINT positive_quantity CHECK(
quantity_on_hand IS NOT NULL
AND
quantity_on_hand >= 0)
);
INSERT INTO product VALUES
('Small Widget', 99, 1, '15-ЯНВ-03' );
INSERT INTO product VALUES
( 'Medium Wodget', 75, 1000, '15-ЯНВ-02' );
INSERT INTO product VALUES
('Chrome Phoobar', 50, 100, '15-ЯНВ-03' );
INSERT INTO product VALUES
('Round Chrome Snaphoo', 25, 10000, null);
INSERT INTO product VALUES
('Extra Huge Mega Phoobar +', 9.95, 1234, '15-ЯНВ-04' );
INSERT INTO product VALUES ('Square Zinculator',
45, 1, TO_DATE ('Декабрь 31, 2002, 11:30',
'Month dd, YYYY, HH:MI'));
INSERT INTO product VALUES (
'Anodized Framifier', 49, 5, NULL);
INSERT INTO product VALUES (
'Red Snaphoo', 1.95, 10, '31-ДЕК-01');
INSERT INTO product VALUES (
'Blue Snaphoo', 1.95, 10, '30-ДЕК-01');
CREATE TABLE purchase (
product_name VARCHAR2(25),
salesperson VARCHAR2(3),
purchase_date DATE,
quantity NUMBER(4,2)
);
ALTER TABLE purchase
ADD PRIMARY KEY (product_name,
salesperson,
purchase_date
);
ALTER TABLE purchase ADD (
CONSTRAINT reasonable_date CHECK(
purchase_date IS NOT NULL
AND
TO_CHAR(purchase_date, 'YYYY-MM-DD') >= '2000-06-30')
);
ALTER TABLE purchase
ADD CONSTRAINT purchase_fk_product FOREIGN KEY
(product_name) REFERENCES product;
ALTER TABLE purchase
ADD CONSTRAINT purchase_fk_person FOREIGN KEY
(salesperson) REFERENCES person;
CREATE INDEX purchase_product
ON purchase(product_name);
CREATE INDEX purchase_salesperson
on purchase(salesperson);
INSERT INTO purchase VALUES
('Small Widget', 'CA', '14-ИЮЛ-03', 1);
INSERT INTO purchase VALUES
('Medium Wodget', 'BB', '14-ИЮЛ-03', 75);
INSERT INTO purchase VALUES
('Chrome Phoobar', 'GA', '14-ИЮЛ-03', 2);
INSERT INTO purchase VALUES
('Small Widget', 'GA', '15-ИЮЛ-03', 8);
INSERT INTO purchase VALUES
('Medium Wodget', 'LB', '15-ИЮЛ-03', 20);
INSERT INTO purchase VALUES
('Round Chrome Snaphoo', 'CA', '16-ИЮЛ-03', 5);
INSERT INTO purchase VALUES
('Small Widget', 'CA', '17-ИЮЛ-03', 1);
CREATE TABLE purchase_archive (
product_name VARCHAR2 (25),
salesperson VARCHAR2(3),
purchase_date DATE,
quantity NUMBER (4, 2)
);
INSERT INTO purchase_archive VALUES
('Round Snaphoo', 'BB', '21-ИЮН-01', 10);
INSERT INTO purchase_archive VALUES
('Large Harflinger ' , 'GA', '22-ИЮН-01', 50);
INSERT INTO purchase_archive VALUES
('Medium Wodget', 'LB', '23-ИЮН-01', 20);
INSERT INTO purchase_archive VALUES
('Small Widget', 'ZZ', '24-ИЮН-02', 80);
INSERT INTO purchase_archive VALUES
('Chrome Phoobar', 'CA', '25-ИЮН-02', 2);
INSERT INTO purchase_archive VALUES
('Small Widget', 'JT', '26-ИЮН-02', 50);

There are few errors i can see.
1) Your Purchase table is not having ORDER_NUMBER column which you are trying to use in your code. Add that column and yoour code should work then.
2) Definition of Audit table is not correct. Its referencing a table which doesnot exist. persoon table doesnot exist. Also AUDIT is a reserve keyword, so it should not be used.
You can check those and compile again.
Error you are getting because of spaces between :OLD. quantity . See the working version of code.
CREATE OR REPLACE TRIGGER audit_trigger
BEFORE INSERT OR UPDATE
ON PURCHASE
FOR EACH ROW
DECLARE
no_name_change EXCEPTION;
quant_change NUMBER (5) := 0;
BEGIN
IF (UPDATING AND (:NEW.product_name <> :OLD.product_name))
THEN
RAISE no_name_change;
END IF;
IF ( ( (UPDATING) AND (:OLD.ORDER_NUMBER IS NULL))
OR ( (INSERTING) AND (:NEW.ORDER_NUMBER IS NULL)))
THEN
SELECT order_num_seq.NEXTVAL INTO :NEW.ORDER_NUMBER FROM DUAL;
END IF;
IF (UPDATING)
THEN
quant_change := :NEW.quantity - :OLD.quantity;
ELSE
quant_change := :NEW.quantity;
END IF;
INSERT INTO audit1
VALUES (:NEW.ORDER_NUMBER,
:NEW.salesperson,
USER,
USERENV ('TERMINAL'),
quant_change,
SYSDATE);
EXCEPTION
WHEN no_name_change
THEN
DBMS_OUTPUT.put_line ('Change of product name not allowed');
DBMS_OUTPUT.put_line ('Aborting and resetting to old values');
:NEW.product_name := :OLD.product_name;
:NEW.salesperson := :OLD.salesperson;
:NEW.ORDER_NUMBER := :OLD.ORDER_NUMBER;
:NEW.quantity := :OLD.quantity;
END audit_trigger;
/

Related

Why it is showing No such column

/* Triggers*/
create table acustomer( id integer primary key, desc text, last_order_id integer);
create table bcustomer ( id integer primary key, item_id int, customer_id int, quan int, price int);
insert into acustomer (desc) values ( 'rohan');
insert into acustomer (desc) values ('mohan');
insert into acustomer (desc) values ('sohan');
select * from acustomer;
create trigger ccustomer after insert on bcustomer
begin
update acustomer set last_order_id = NEW.id where acustomer.id = NEW.customer_id;
end;
insert into bcustomer (item_id, customer_id, quan, price) values (1, 2, 3, 4);
insert into bcustomer (item_id, customer_id, quan, price) values (5, 6, 7, 8);
insert into bcustomer (item_id, customer_id, quan, price) values (8, 9, 10, 20);
insert into bcustomer (item_id, customer_id, quan, price) values (4, 12, 19, 13);
select * from acustomer;
select * from bcustomer;
#On executing insertion in table ccustomer, it is showing error : no such column : NEW.customer.id
Your last insert for bcustomer table is
insert into bcustomer (item_id, customer_id, quan, price) values (4, 12, 19, 13);
which doesn't have any matching last_order_id in acustomer.
If you will run
insert into bcustomer (item_id, customer_id, quan, price) values (4, 1, 19, 13);
customer_id = 1, it will update your acustomer table since it has a matching id, which is 1.
try this dbfiddle.

To find passengers travelling more than thrice on the same route in PL/SQL

Here I am creating three tables, one for storing the Train Info. Another for holding onto the Passenger info and the other one to hold the ticket Info.
create table T_Train_Info(
route_no integer primary key,
source varchar2(50),
destination varchar2(50)
)
create table T_Pay_Info(
pax_id integer primary key,
pax_name varchar2(50),
dob date,
gender varchar2(5)
)
create table T_Tkt_Info(
pax_id integer,
route_no integer,
journey_date date,
seat_no varchar2(5),
primary key(pax_id, route_no, journey_date)
)
In the Train_Info table, I am inserting two unique routes with the same source and destination as there can be different routes for the same source and destination. And filling the other tables in the same manner. In the ticket table, I am repeating values because I aim to find the passenger travelling thrice on the same route.
insert into T_Train_Info values(1, 'Chennai', 'Pune');
insert into T_Train_Info values(2, 'Chennai', 'Pune');
insert into T_Train_Info values(3, 'Bangalore', 'Kolkata');
insert into T_Tkt_Info values(100, 1, to_date('11/03/2022', 'DD/MM/YYYY'), 22);
insert into T_Tkt_Info values(100, 1, to_date('14/08/2022', 'DD/MM/YYYY'), 23);
insert into T_Tkt_Info values(100, 1, to_date('29/08/2022', 'DD/MM/YYYY'), 24);
insert into T_Tkt_Info values(102, 3, to_date('22/08/2022', 'DD/MM/YYYY'), 24);
insert into T_Tkt_Info values(100, 1, to_date('27/08/2022', 'DD/MM/YYYY'), 24);
insert into T_Tkt_Info values(100, 2, to_date('28/08/2022', 'DD/MM/YYYY'), 24);
insert into T_Pay_Info values(100, 'A', to_date('11/03/2022', 'DD/MM/YYYY'), 'F');
insert into T_Pay_Info values(101, 'B', to_date('23/09/2023', 'DD/MM/YYYY'), 'M');
insert into T_Pay_Info values(102, 'A', to_date('11/03/2022', 'DD/MM/YYYY'), 'F');
insert into T_Pay_Info values(103, 'D', to_date('23/09/2023', 'DD/MM/YYYY'), 'M');
insert into T_Pay_Info values(104, 'A', to_date('11/03/2022', 'DD/MM/YYYY'), 'F');
insert into T_Pay_Info values(105, 'A', to_date('23/09/2023', 'DD/MM/YYYY'), 'M');
Here's my procedure which keeps returning the error saying 'exact fetch returns more than requested number of rows' at the select statement. What am I doing wrong here?
create or replace procedure pr_pass_route_details(x in T_Train_Info.Source%type, y in T_Train_Info.Destination%type) is
pr_name T_Pay_Info.Pax_Name%type;
begin
for i in (select pax_id from t_tkt_info group by pax_id,route_no having count(*) >=3) loop
select pax_name into pr_name from t_pay_info where pax_id = i.pax_id and T_Train_Info.Source=x and T_Train_Info.Destination=y;
dbms_output.put_line(pr_name);
end loop;
end pr_pass_route_details;
i’m not sure why you’ve written a SP to do this as you can achieve this with a simple query:
SELECT
pax_id,
route_no,
COUNT(journey_date)
FROM T_Tkt_Info
GROUP BY
pax_id,
route_no
HAVING COUNT(journey_date) = 3

Analytical Query in SQL for MIN, MAX, and AVG

I am trying to figure out a query for this question: for each major, list the number of students, minimum GPA, maximum GPA, average GPA, minimum age, maximum age, and average age. (Show GPA with 2 decimal points, age with no decimal points. You may find it useful to create a view with one of the previous queries for this one.)
This is the script to create the table for SQL!
REM drop all the tables. Note that you need to drop the
REM dependent table first before dropping the base tables.
drop table Reg;
drop table Student;
drop table Course;
REM Now create all the tables.
create table Student
(
sid char(10) primary key,
sname varchar(20) not null,
gpa float,
major char(10),
dob DATE
);
create table Course
(
cno char(10) primary key,
cname varchar(20) not null,
credits int,
dept char(10)
);
create table Reg
(
sid references Student(sid) on delete cascade,
cno references Course(cno) on delete cascade,
grade char(2),
primary key (sid, cno)
);
REM Now insert all the rows.
insert into Student values ('111', 'Joe', 3.5 , 'MIS', '01-AUG-2000');
insert into Student values ('222', 'Jack', 3.4 , 'MIS', '12-JAN-1999');
insert into Student values ('333', 'Jill', 3.2 , 'CS', '15-MAY-1998');
insert into Student values ('444', 'Mary', 3.7 , 'CS', '17-DEC-2001');
insert into Student values ('555', 'Peter', 3.8 , 'CS', '19-MAR-1999');
insert into Student values ('666', 'Pat', 3.9, 'Math', '31-MAY-2000');
insert into Student values ('777', 'Tracy', 4.0, 'Math', '18-JUL-1997');
insert into Course values ('c101', 'intro', 3 , 'CS');
insert into Course values ('m415', 'database', 4 , 'Bus');
insert into Course values ('m215', 'programming', 4 , 'Bus');
insert into Course values ('a444', 'calculus', 3 , 'Math');
insert into Reg values ('111', 'c101', 'A');
insert into Reg values ('111', 'm215', 'B');
insert into Reg values ('111', 'm415', 'A');
insert into Reg values ('222', 'm215', 'A');
insert into Reg values ('222', 'm415', 'B');
insert into Reg values ('333', 'c101', 'A');
insert into Reg values ('444', 'm215', 'C');
insert into Reg values ('444', 'm415', 'B');
insert into Reg values ('555', 'c101', 'B');
insert into Reg values ('555', 'm215', 'A');
insert into Reg values ('555', 'm415', 'A');
insert into Reg values ('666', 'c101', 'A');
This is what I have so far:
SELECT major,
count(distinct SID) as students,
round(min(gpa), 2),
round(max(gpa), 2),
round(avg(gpa), 2),
trunc(min(sysdate - dob)/365) as min_age,
trunc(max(sysdate - dob)/365) as max_age,
trunc(avg(sysdate - dob)/365) as avg_age,
FROM Student
GROUP BY MAJOR;
According to your input I've made a query that I belive will show you the results. (It was kind hard to read the tables the way you posted it). The syntax may differ according to your DBMS (SQL Server, MySQL, REdshift, Postgres, etc)
Here is the query:
SELECT major,
COUNT(*) as students,
ROUND(MIN(gpa), 2) as min_gpa,
ROUND(MAX(gpa), 2) as max_gpa,
ROUND(AVG(gpa), 2) as avg_gpa,
MIN(DATEDIFF(year, current_date, dob)) as min_age,
MAX(DATEDIFF(year, current_date, dob)) as max_age,
AVG(DATEDIFF(year, current_date, dob)) as avg_date
FROM students st left join Course co on co.dept = st.major
GROUP BY major
Your query is completely fine (just remove comma(,) after avg_age.
SELECT major,
count(distinct SID) as students,
round(min(gpa), 2) as MinGPA,
round(max(gpa), 2) as MaxGPA,
round(avg(gpa), 2) as AvgGPA,
round(min(sysdate - dob)/365,0) as min_age,
round(max(sysdate - dob)/365,0) as max_age,
round(avg(sysdate - dob)/365,0) as avg_age
FROM Student
GROUP BY MAJOR;
You can also use months_between() with floor() to get the same result:
select * from student;
SELECT major,
count(distinct SID) as students,
round(min(gpa), 2) as MinGPA,
round(max(gpa), 2) as MaxGPA,
round(avg(gpa), 2) as AvgGPA,
floor(min(months_between(trunc((sysdate)), dob)) /12) as min_age,
floor(max(months_between(trunc((sysdate)), dob)) /12) as max_age,
floor(avg(months_between(trunc((sysdate)), dob)) /12) as avg_age
FROM Student
GROUP BY MAJOR;

Using multiple foreign keys in a SQL select statement

I have four tables, one of them named matches and another one named teams. I need to display the teamCode in teams with the number of point they have that we can calculate in matches. Each win is 2 points each draw one point and each lost zero.
CREATE TABLE divisions
(
codediv CHAR(1) NOT NULL,
nomdiv VARCHAR2(40)
);
ALTER TABLE divisions
ADD CONSTRAINT divisions_pk PRIMARY KEY (codediv);
CREATE TABLE teams
(
teamCode CHAR(3) NOT NULL,
teamName VARCHAR2(50),
codediv CHAR(1) NOT NULL,
ville VARCHAR2(40),
nbcoupes NUMBER
);
ALTER TABLE teams ADD CHECK (nbcoupes >= 0);
ALTER TABLE teams ADD CONSTRAINT teams_pk PRIMARY KEY (teamCode);
CREATE TABLE joueurs
(
numjoueur NUMBER(3) NOT NULL,
nom VARCHAR2(30),
prenom VARCHAR2(30),
codeequipe CHAR(3)
);
ALTER TABLE joueurs ADD CONSTRAINT joueurs_pk PRIMARY KEY (numjoueur);
CREATE TABLE matchs
(
MatchNumber NUMBER(4) NOT NULL,
datematch DATE,
codeVisitingTeam CHAR(3) NOT NULL,
codeReceivingTeam CHAR(3) NOT NULL,
scoreVisitingTeam NUMBER(2),
scoreReceivingTeam NUMBER(2)
);
ALTER TABLE matchs ADD CONSTRAINT matchs_pk PRIMARY KEY (MatchNumber);
CREATE TABLE statistiques
(
nummatch NUMBER(4) NOT NULL,
numjoueur NUMBER(3) NOT NULL,
nbbuts NUMBER(3),
nbpasse NUMBER(3)
);
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_pk PRIMARY KEY (numjoueur, nummatch);
ALTER TABLE matchs
ADD CONSTRAINT codeVisitingTeam FOREIGN KEY ( codeVisitingTeam)
REFERENCES teams ( teamCode );
ALTER TABLE teams
ADD CONSTRAINT teams_divisions_fk FOREIGN KEY ( codediv )
REFERENCES divisions ( codediv );
ALTER TABLE joueurs
ADD CONSTRAINT joueurs_equipes_fk FOREIGN KEY ( teamCode )
REFERENCES equipes ( teamCode );
ALTER TABLE matchs
ADD CONSTRAINT matchs_equipes_fk FOREIGN KEY ( CodeReceivingTeam )
REFERENCES equipes ( teamCode );
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_joueurs_fk FOREIGN KEY ( numjoueur )
REFERENCES joueurs ( numjoueur );
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_matchs_fk FOREIGN KEY ( nummatch )
REFERENCES matchs ( nummatch );
insert into divisions values('O', 'OUEST');
insert into divisions values('E', 'EST');
insert into equipes values('MTL', 'LES CANADIENS DE MONTRÉAl', 'E', 'MONTRÉAl', 24);
insert into equipes values('TOR', 'LES MAPLE LEAFS', 'E', 'TORONTO', 22);
insert into equipes values('OTT', 'LES SÉNATEURS', 'E', 'OTTAWA', 4);
insert into equipes values('AVL', 'LES AVALANCHES', 'O', 'COLORADO', 2);
insert into equipes values('VAN', 'LES CANUKS', 'O', 'VANCOUVER', 1);
insert into equipes values('BRU', 'LES BRUNS DE BOSTON', 'E', 'BOSTON', 13);
insert into Joueurs values(1, 'PRICE', 'CAREY', 'MTL');
insert into Joueurs values(2, 'MARKOV', 'ANDRÉ', 'MTL');
insert into Joueurs values(3, 'SUBBAN', 'KARL', 'MTL');
insert into Joueurs values(4, 'PATIORETTY', 'MAX', 'MTL');
insert into Joueurs values(10, 'HAMMOND', 'ANDREW', 'OTT');
insert into Joueurs values(6, 'STONE', 'MARC', 'OTT');
insert into Joueurs values(9, 'TURIS', 'KYLE', 'OTT');
insert into Joueurs values(7, 'GALLAGHER', 'BRANDON', 'MTL');
insert into Joueurs values(8, 'TANGUAY', 'ALEX', 'AVL');
insert into Joueurs values(11, 'THOMAS', 'BIL', 'AVL');
insert into Joueurs values(5, 'PATOCHE', 'ALAIN', NULL);
insert into Joueurs values(12, 'POIRIER', 'JUTEUX', NULL);
insert into Matchs values(100, TO_DATE('18-10-30', 'YY/MM/DD'), 'MTL', 'TOR', 3 , 4);
insert into Matchs values(101, TO_DATE('18-11-10', 'YY/MM/DD'), 'TOR', 'MTL', 3 , 3);
insert into Matchs values(102, TO_DATE('18-10-12', 'YY/MM/DD'), 'MTL', 'OTT', 2 , 0);
insert into Matchs values(103, TO_DATE('18-10-20', 'YY/MM/DD'), 'OTT', 'MTL', 0 , 1);
insert into Matchs values(104, TO_DATE('18-11-30', 'YY/MM/DD'), 'MTL', 'AVL', 3 , 4);
insert into Matchs values(105, TO_DATE('18-11-10', 'YY/MM/DD'), 'AVL', 'MTL', 0 , 0);
insert into Matchs values(106, TO_DATE('18-12-12', 'YY/MM/DD'), 'MTL', 'VAN', 2 , 0);
insert into Matchs values(107, TO_DATE('18-03-17', 'YY/MM/DD'), 'VAN', 'MTL', 3 , 1);
insert into Matchs values(108, TO_DATE('18-11-30', 'YY/MM/DD'), 'OTT', 'VAN', 0 , 0);
insert into Matchs values(109, TO_DATE('18-11-10', 'YY/MM/DD'), 'OTT', 'TOR', 0 , 4);
insert into Matchs values(114, TO_DATE('18-10-30', 'YY/MM/DD'), 'BRU', 'TOR', 3 , 4);
insert into Matchs values(115, TO_DATE('19-02-15', 'YY/MM/DD'), 'AVL', 'TOR', null , null);
insert into Matchs values(120, TO_DATE('18-02-26', 'YY/MM/DD'), 'MTL', 'AVL', null , null);
insert into Matchs values(121, TO_DATE('19-02-20', 'YY/MM/DD'), 'MTL', 'OTT', null , null);
Insert into statistiques values(100,3,2,2);
Insert into statistiques values(100,7,1,1);
Insert into statistiques values(101,3,1,0);
Insert into statistiques values(101,7,0,1);
Insert into statistiques values(101,4,1,2);
Insert into statistiques values(101,2,1,2);
Insert into statistiques values(100,4,0,2);
Insert into statistiques values(102,3,1,1);
Insert into statistiques values(102,7,1,2);
Insert into statistiques values(102,9,0,1);
Insert into statistiques values(106,4,1,1);
Insert into statistiques values(106,3,0,2);
Insert into statistiques values(106,2,1,0);
Insert into statistiques values(100,1,null,null);
Insert into statistiques values(101,1,null,null);
Insert into statistiques values(103,1,null,null);
Insert into statistiques values(102,1,null,null);
I've started with this to get the winning teams
select *
from
(select v.teamcode, count(m.codeVisitingTeam) as WonMatches
from matchs m
join teams v on v.teamCode = m.codeVisitingTeam
where m.scoreVisitingTeam > m.scoreReceivingTeam
group by v.teamCode
union all
select r.codeequipe, count(m.codeequiper) as WonMatches
from matchs m
join teams r on r.teamCode = m.codeReceivingTeam
where m.scoreReceivingTeam > m.scoreVisitingTeam
group by r.teamCode));
The only problem with the code above is that it returns twice the team 'MTL' as so :
VAN 1
MTL 2
AVL 1
TOR 3
MTL 1
So I was having a bit of fun with your query and did a bit more than you asked. I wrote the following query to calculated the full complement of wins, losses, and ties. I then ordered the results by points (3 points for a win and 1 for a draw). I hope this helps you a bit:
SELECT *
FROM (SELECT TeamCode,
CASE
WHEN (team = 'VISTING' AND scoreVisitingTeam > SCORERECEIVINGTEAM) OR (team = 'RECEIVING' AND SCORERECEIVINGTEAM > SCOREVISITINGTEAM) THEN 'WIN'
WHEN (team = 'VISTING' AND scoreVisitingTeam < SCORERECEIVINGTEAM) OR (team = 'RECEIVING' AND SCORERECEIVINGTEAM < SCOREVISITINGTEAM) THEN 'LOSS'
ELSE 'DRAW'
END AS RESULT
FROM matchs
UNPIVOT (TeamCode FOR Team IN (CodeVisitingTeam AS 'VISTING', CodeReceivingTeam AS 'RECEIVING')))
PIVOT(COUNT(*) FOR RESULT IN ('WIN' AS WINS, 'LOSS' AS LOSSES, 'DRAW' AS DRAWS))
ORDER BY (wins*3)+draws DESC;
If you have questions, please let me know.
I also created a SQLFiddle. (Link) Note: I removed your constraints from the SQLFiddle. They were throwing errors and I didn't feel like debugging it.
You can do it in a single query with conditional aggregation:
select e.teamCode,
sum(
case
when (e.teamCode = m.codeReceivingTeam and m.scoreReceivingTeam > m.scoreVisitingTeam)
or (e.teamCode = m.codeVisitingTeam and m.scoreReceivingTeam < m.scoreVisitingTeam) then 2
when m.scoreReceivingTeam = m.scoreVisitingTeam then 1
else 0
end
) total_points
from equipes e inner join matchs m
on e.teamCode in (m.codeReceivingTeam, m.codeVisitingTeam)
group by e.teamCode

SQL Trigger Statement will create but will not run

---create EMPLOYEE table---
CREATE TABLE EMPLOYEES
(
EMPLOYEEID INT NOT NULL,
EMPLOYNAME VARCHAR2(25) NULL,
EMPLOYAGE INT NULL,
EMPLOYADDRESS VARCHAR2(25) NULL,
SALARY NUMBER(9,2) DEFAULT (0) NULL,
CONSTRAINT EMPLOYEES_PK PRIMARY KEY(EMPLOYEEID)
);
--INSERT EMPLOYEES--
INSERT INTO EMPLOYEES
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00);
INSERT INTO EMPLOYEES
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00);
INSERT INTO EMPLOYEES
VALUES (3, 'Kaushik', 24, 'Kota', 2000.00);
INSERT INTO EMPLOYEES
VALUES (4,'Chaitali', 25, 'Mumbai', 6500.00);
INSERT INTO EMPLOYEES
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00);
INSERT INTO EMPLOYEES
VALUES (6, 'Komal', 22, 'MP', 4500.00);
--CREATE TRIGGER FOR AN UPDATE TO THE SALARY--
CREATE OR REPLACE TRIGGER display
BEFORE DELETE OR INSERT OR UPDATE ON EMPLOYEES
FOR EACH ROW
WHEN (NEW.employeeid >0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
End;
--triggering trigger with insert--
INSERT INTO EMPLOYEES (EMPLOYEEID,EMPLOYNAME,EMPLOYAGE, EMPLOYADDRESS, SALARY)
VALUES(9,'Kri', 67, 'PK', 7900.00);
UPDATE EMPLOYEES
SET SALARY = SALARY +500
WHERE EMPLOYEEID = 4;
this code will all compile in SQL developer but when I try to update and run any of the code it will not run. I enable it through the trigger tab in developer, so it should be working fine. Any help is appreciated because I am teaching this to my self.
thanks
RMan2015