SQL multiply 2 columns 2 different tables - sql

What i am trying to do is calculate diner_payment_due (DINER TABLE), by multiplying food_serve_cost (FOOD_SERVE TABLE) by food_serve_size (FS_DINER TABLE)
CREATE TABLE diner (
diner_no NUMBER(8) NOT NULL,
diner_payment_due NUMBER(6,2) NOT NULL,
diner_seat_no NUMBER(2) NOT NULL,
diner_seated DATE NOT NULL,
diner_completed DATE,
table_no NUMBER(2) NOT NULL
);
CREATE TABLE food_serve (
food_item_no NUMBER(4) NOT NULL,
food_serve_size CHAR(2) NOT NULL,
food_serve_kilojoules NUMBER(4) NOT NULL,
food_serve_cost NUMBER(5,2) NOT NULL
);
CREATE TABLE FS_DINER (
DINER_NO NUMBER(8) NOT NULL,
FOOD_ITEM_NO NUMBER(4) NOT NULL,
FOOD_SERVE_SIZE CHAR(2 BYTE) NOT NULL,
FS_DINER_NO_SERVES NUMBER(1) NOT NULL,
FS_DINER_ITEM_SERVED CHAR (1) NOT NULL,
CONSTRAINT pk_fs_diner PRIMARY KEY (DINER_NO, FOOD_ITEM_NO,FOOD_SERVE_SIZE)
);
I just need to return a single values and then insert into the diner table, i'm thinking that I need to do a Inner Join, then simply sum (food_serve_cost * NO_SERVES) then group by DINER_NO ?
INSERT INTO DINER ( DINER_NO, DINER_PAYMENT_DUE, DINER_SEAT_NO, DINER_SEATED, DINER_COMPLETED, TABLE_NO) INSERT INTO DINER VALUES (1, SELECT SUM (FOOD_SERVE.FOOD_SERVE_COST * FS_DINER..., , 1, 1/05/2017, 1 /05/2017, 1);

Am updating diner table based on the value from other two tables.
INSERT INTO DINER
(SELECT fs.diner_no,
(fs.food_serve_cost * fd.FOOD_SERVE_SIZE),
11,sysdate,sysdate,11 /*Am assuming, Due to Not null constraint, there will be error*/
FROM food_serve fs,
FS_DINER fd
WHERE fs.food_item_no = fd.food_item_no)

Related

Create trigger which updates a separate "audit table" automatically after update of a table

My tables are
Book
CREATE TABLE Book
(
Bk_id CHAR(06) NOT NULL,
BK_Name VARCHAR(60) NOT NULL,
Author VARCHAR(30) NOT NULL,
Price NUMERIC(03) NOT NULL,
No_of_copies NUMERIC(02) NOT NULL,
CONSTRAINT Book_PK PRIMARY KEY (Bk_id)
);
Location
CREATE TABLE Location
(
Loc_id CHAR(06) NOT NULL,
Loc_Name VARCHAR(15) NOT NULL,
Stock NUMERIC(02) NOT NULL,
CONSTRAINT Location_PK PRIMARY KEY (Loc_id)
);
Customer
CREATE TABLE Customer
(
Cus_id CHAR(06) NOT NULL,
Cus_Name VARCHAR(25) NOT NULL,
Gender VARCHAR(06) NOT NULL,
TP CHAR(12) NOT NULL,
Address VARCHAR(40) NOT NULL,
CONSTRAINT Customer_PK PRIMARY KEY (Cus_id)
);
Copy
CREATE TABLE Copy
(
Copy_id CHAR(06) NOT NULL,
Bk_id CHAR(06) NOT NULL,
Loc_id CHAR(06) NOT NULL,
Opinion CHAR(02) NOT NULL,
CONSTRAINT pk_Copy PRIMARY KEY (Copy_id),
CONSTRAINT fk_Copy_Bk_id_FK FOREIGN KEY (Bk_id) REFERENCES Book(Bk_id),
CONSTRAINT fk_Copy_Loc_id_FK FOREIGN KEY (Loc_id) REFERENCES Location(Loc_id)
);
Borrow
CREATE TABLE Borrow
(
Cus_evo NUMERIC(02) NOT NULL,
B_Date DATE NOT NULL,
R_Date DATE NOT NULL,
Fee NUMERIC(03) NOT NULL,
Copy_id CHAR(06) NOT NULL,
Cus_id CHAR(06) NOT NULL,
CONSTRAINT pk_Borrow PRIMARY KEY (Cus_id,Copy_id),
CONSTRAINT fk_Borrow_Copy_id_FK FOREIGN KEY (Copy_id) REFERENCES Copy(Copy_id),
CONSTRAINT fk_Borrow_Cus_id_FK FOREIGN KEY (Cus_id) REFERENCES Customer(Cus_id)
);
Audit_Table
Create table Audit_Table
(
Cus_Name VARCHAR(25) NOT NULL,
BK_Name VARCHAR(60) NOT NULL,
B_Date DATE NOT NULL,
Loc_Name VARCHAR(15) NOT NULL,
Cus_evo NUMERIC(02) NOT NULL
);
If a customer gives a zero evaluationCus_evo=0, the details of their Borrowing (Cus_Name from CUSTOMER, the BK_Name from Book, B_Date from Borrow, Loc_Name of the copy from Location and Cus_evo from Borrow) must be placed in an audit table.
The trigger that I created:
CREATE OR REPLACE TRIGGER "AUDIT_TRIGGER"
BEFORE
INSERT OR UPDATE ON Borrow
FOR EACH ROW
WHEN (new.Cus_evo = 0)
BEGIN
INSERT INTO Audit_Table
VALUES (:OLD.Cus_Name, :OLD.BK_Name, :OLD.B_Date, :OLD.Loc_Name, :OLD.Cus_evo);
END;
/
I get this error:
Errors: TRIGGER AUDIT_TRIGGER
Line/Col: 3/9 PLS-00049: bad bind variable 'OLD.CUS_NAME'
Line/Col: 3/24 PLS-00049: bad bind variable 'OLD.BK_NAME'
Line/Col: 3/51 PLS-00049: bad bind variable 'OLD.LOC_NAME'
Those variables reference columns on other tables. So they are not available in the namespace of the borrow :OLD namespace. So what you need to do is write a query which looks up those tables using the foreign key values from the borrow record. Something like this:
CREATE OR REPLACE TRIGGER "AUDIT_TRIGGER"
BEFORE
INSERT OR UPDATE ON Borrow
FOR EACH ROW
WHEN (new.Cus_evo = 0)
BEGIN
INSERT INTO Audit_Table
select cus.Cus_Name, book.BK_Name, :NEW.B_Date, loc.Loc_Name, :NEW.Cus_evo
from customer cus
cross join location loc
cross join copy
cross join book
where cus.cus_id = :new.cus_id
and copy.copy_id = :new.copy_id
and book.bk_id = copy.bk_id
and loc.loc_id = copy.loc_id
END;
/
Note that I suggest the :NEW namespace. That is the appropriate one for INSERTING actions, and also fits your use case when UPDATING.

How to make (patient id) forgein key in table of bill?

I try to create three tables by using website suport compiler any code but I have a problem in the table of the bill.
When I run it I get to error show me it is near in foreign key
These are codes of three tables
CREATE TABLE patient (
Patient Id (5) Primary key,
Name Varchar (20) Not null ,
Age Int Not null ,
Weight Int Not null ,
Gender Varchar (10) Not null,
Address Varchar (50) Not null ,
Disease Varchar (20) Not null
);
CREATE TABLE doctors (
DoctorId Varchar (5) Primary key,
Doctorname Varchar (15) Not null,
Dept Varchar (15) Not null
);
CREATE TABLE bill (
Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5) Foreign key,,
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null
);
Patient Table
CREATE TABLE patient
(
patient_id VARCHAR (5) PRIMARY KEY,
name VARCHAR (20) NOT NULL,
age INT NOT NULL,
weight INT NOT NULL,
gender VARCHAR (10) NOT NULL,
address VARCHAR (50) NOT NULL,
disease VARCHAR (20) NOT NULL
);
Errors
No data type has been assigned in Patient id column (Patient Id (5)
Primary key)
Patient id column name contains spaces. You need to
enclose the column name in double quotes or replace space with something else
(ex: _). It's not recommended to use spaces.
A column name with space
CREATE TABLE tablename ("column name" datatype);
Doctors Table
CREATE TABLE doctors
(
doctorid VARCHAR (5) PRIMARY KEY,
doctorname VARCHAR (15) NOT NULL,
dept VARCHAR (15) NOT NULL
);
Bill Table
CREATE TABLE bill
(
bill_no VARCHAR (50) PRIMARY KEY,
patient_id VARCHAR (5),
doctor_charge INT NOT NULL,
patient_type VARCHAR (10) NULL,
no_of_days INT NULL,
lab_charge INT NULL,
bill INT NOT NULL,
FOREIGN KEY (patient_id) REFERENCES patient(patient_id)
);
Errors
The way you have assigned foreign key is wrong. Please refer this and this article for more information. (Patient_Id Varchar (5) Foreign key,,)
There are two commans in the Patient_Id column (Patient_Id Varchar (5) Foreign key,,)
You have to provide reference of the table for which you want to use the reference key.
For example, you have table Persons which has Primary key PersonID, in that case if you want to use that as foreign key in another table, lets say Orders.
In Oracle
CREATE TABLE Orders (
OrderID numeric(10) not null,
OrderNumber numeric(10) not null,
PersonID numeric(10) not null,
CONSTRAINT fk_person_id
FOREIGN KEY (PersonID )
REFERENCES Persons(PersonID )
Your Case :
CREATE TABLE bill
( Bill_no Varchar (50) Primary key,
Patient_Id Varchar (5),
doctor_charge Int Not null,
patient_type Varchar (10) null,
no_of_days Int null,
lab_charge Int null,
bill Int Not null,
CONSTRAINT fk_patient_id
FOREIGN KEY (Patient_Id)
REFERENCES patient(Patient_Id)
);
Remove the 'Foreign Key' from the table creation script.
Add this to your SQL script:
ALTER TABLE [Bill] WITH CHECK ADD CONSTRAINT [FK_Bill_Patient] FOREIGN KEY([Patient_Id])
REFERENCES [Patient] ([Patient_Id])
GO
ALTER TABLE [Bill] CHECK CONSTRAINT [FK_Bill_Patient]
GO
The words FOREIGN KEY are only needed for introducing the name of the FK constraint. Since your other constraints are not named, you might as well skip that part and go straight to REFERENCES.
If you specify a foreign key constraint as part of the column definition, you can omit the datatype to allow it to inherit from its parent at the time of creation, which I think is good practice as the types will automatically match.
We use VARCHAR2 in Oracle, not VARCHAR.
You don't need to specify NULL for columns that are allowed to be null.
I am not sure a 5-character string is a good datatype for a unique ID. How will you generate the values? Normally an auto-incrementing sequence number simplifies this.
create table doctors
( doctorid varchar2(5) primary key
, doctorname varchar2(15) not null
, dept varchar2(15) not null );
create table patients
( patient_id varchar2(5) primary key
, name varchar2(20) not null
, age integer not null
, weight integer not null
, gender varchar2(10) not null
, address varchar2(50) not null
, disease varchar2(20) not null );
create table bills
( bill_no varchar2(50) primary key
, patient_id references patients -- Allow datatype to inherit from parent
, patient_type varchar2(10)
, no_of_days integer
, lab_charge integer
, bill integer not null );

New to SQL, Need to check schoolwork on Fiddle - Is my code correct?

CREATE TABLE Customer_Master (
customer_ID INTEGER(30) NOT NULL AUTO_INCREMENT,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
street_address VARCHAR(100) NOT NULL,
apt INTEGER(9),
city VARCHAR(30) NOT NULL,
state VARCHAR(3) NOT NULL,
zip VARCHAR(10) NOT NULL,
home_phone INTEGER NOT NULL,
mobile_phone INTEGER(10) NOT NULL,
other_phone INTEGER(10) NOT NULL,
PRIMARY KEY (customer_ID)
);
CREATE TABLE Order_Master (
Donut_order_ID INTEGER(10) NOT NULL,
Order_date DATETIME NOT NULL,
Special_notes VARCHAR(255) NOT NULL,
Customer_ID INTEGER(30) NOT NULL,
PRIMARY KEY (Donut_order_ID),
FOREIGN KEY (Customer_ID) REFERENCES Customer_Master(Customer_ID)
);
CREATE TABLE Donut_Master (
Donut_ID VARCHAR(10) NOT NULL,
Name VARCHAR(30) NOT NULL,
Unit_price NUMERIC(10,2) NOT NULL,
PRIMARY KEY (Donut_ID)
);
CREATE TABLE Order_Details (
Donut_Order_ID INTEGER(10) NOT NULL,
Donut_ID VARCHAR(10) NOT NULL,
Quantity INTEGER(100) NOT NULL,
FOREIGN KEY (Donut_Order_ID) REFERENCES Order_Master (Donut_Order_ID),
FOREIGN KEY (Donut_ID) REFERENCES Donut_Master (Donut_ID)
);
CREATE VIEW Customer_Information AS
SELECT CONCAT (first_name,'',last_name) AS Customer_Name,
customer_ID, street_address, apt, city, state, zip, home_phone, mobile_phone, other_phone
FROM Customer_Master;
CREATE INDEX Donut
ON Donut_Master (Donut_ID);
INSERT INTO Customer_Master
VALUES
('1','Bruce','Wayne','123_Gotham','12','Gotham_City',
'NY','12345','123456789','000000000','000000000');
INSERT INTO Order_Master
VALUES ('1','2017-05-11','Please_include_plates_and_napkins','1');
INSERT INTO Donut_Master
VALUES
('1','Plain','1.50'),
('2','Glazed','1.75'),
('3','Cinnamon','1.75'),
('4','Chocolate','1.75'),
('5','Sprinkle','1.75'),
('6','Gluten-Free','2.00');
INSERT INTO Order_Details
VALUES ('1','1','1');
Well, the errors that you get should be clear enough to fix any mistakes.
There are some typos, like an extra comma in the CREATE statement of table Donut_Master and the Customer_ID of Order_Details is varchar and in Customer_Master is int. I think your INSERT statement is incomplete too, see here: https://www.w3schools.com/sql/sql_insert.asp
These are some great lessons actually that you can go through! Best of luck!

INSERT statements gives me different errors

I'm trying to run a file which contains INSERT statements. The statements will either give me an not enough values error or unique constraint error.
Below is my create table statement:
CREATE TABLE PART
(PNum VARCHAR(25) NOT NULL,
PName VARCHAR(75) NOT NULL,
PUnitPrice NUMBER(7,2) NOT NULL,
ComponentOf VARCHAR(25),
CONSTRAINT PART_PKEY PRIMARY KEY(PNum),
CONSTRAINT PART_FKEY FOREIGN KEY(ComponentOf)
REFERENCES PART(PNum)
};
CREATE TABLE MANUFACTURER
(MName VARCHAR(50) NOT NULL,
MAddress VARCHAR(100) NOT NULL,
MPhone VARCHAR(25) NOT NULL,
CONSTRAINT MANUFACTURER_PKEY PRIMARY KEY(MName),
);
CREATE TABLE PART-MANUFACTURED
(MDate DATE,not null
PNum VARCHAR(25) NOT NULL,
MName VARCHAR(50) NOT NULL,
Quantity NUMBER(10) NOT NULL,
CONSTRAINT PART-MANUFACTURED_PKEY PRIMARY KEY(MName,PNum,MDate),
CONSTRAINT PART-MANUFACTURED_FKEY1 FOREIGN KEY(PNum)
REFERENCES PART(PNum),
CONSTRAINT PART-MANUFACTURED_FKEY2 FOREIGN KEY(MName)
REFERENCES MANUFACTURER(MName)
);
CREATE TABLE CUSTOMER
(CNum VARCHAR(25) NOT NULL,
CName VARCHAR(75) NOT NULL,
CType VARCHAR(20) NOT NULL,
CONSTRAINT CUSTOMER_PKEY PRIMARY KEY(CNum),
CONSTRAINT CHECK_CType
CHECK(CType IN (‘INDIVIDUAL,’INSTITUITION’))
);
CREATE TABLE ORDERS
(CNum VARCHAR(25) NOT NULL,
PNum VARCHAR(25) NOT NULL,
OrderDate DATE NOT NULL,
OrderQuantity NUMBER(7,2) NOT NULL,
CONSTRAINT ORDERS_PKEY PRIMARY KEY(CNum,PNum,OrderDate),
CONSTRAINT ORDERS_FKEY1 FOREIGN KEY(CNum)
REFERENCES CUSTOMER(CNum),
CONSTRAINT ORDERS_FKEY2 FOREIGN KEY(PNum)
REFERENCES PART(PNum)
);
Below is the statement that gives me the not enough values error:
INSERT INTO PART
VALUES('S001','System-Economy',1100,null);
INSERT INTO PART
VALUES('M001','Monitor-17 inch',250,'S001');
For the unique constraints error, I believe i have to insert the data in order of their primary and referencing keys right?
So what do I need to change in order for the the insert statements to work?
I dont see any error on Insert. The problem is with your create table. Plenty to correct. Try this
CREATE TABLE PART ( PNUM VARCHAR ( 25 ) NOT NULL,
PNAME VARCHAR ( 75 ) NOT NULL,
PUNITPRICE NUMBER ( 7, 2 ) NOT NULL,
COMPONENTOF VARCHAR ( 25 ),
CONSTRAINT PART_PKEY PRIMARY KEY ( PNUM ),
CONSTRAINT PART_FKEY FOREIGN KEY
( COMPONENTOF )
REFERENCES PART ( PNUM ) );
CREATE TABLE MANUFACTURER ( MNAME VARCHAR ( 50 ) NOT NULL,
MADDRESS VARCHAR ( 100 ) NOT NULL,
MPHONE VARCHAR ( 25 ) NOT NULL,
CONSTRAINT MANUFACTURER_PKEY PRIMARY KEY ( MNAME ) );
CREATE TABLE PART_MANUFACTURED ( MDATE DATE NOT NULL,
PNUM VARCHAR ( 25 ) NOT NULL,
MNAME VARCHAR ( 50 ) NOT NULL,
QUANTITY NUMBER ( 10 ) NOT NULL,
CONSTRAINT PART_MANUFACTURED_PKEY PRIMARY KEY
( MNAME, PNUM, MDATE ),
CONSTRAINT PART_MANUFACTURED_FKEY1 FOREIGN KEY
( PNUM )
REFERENCES PART ( PNUM ),
CONSTRAINT PART_MANUFACTURED_FKEY2 FOREIGN KEY
( MNAME )
REFERENCES MANUFACTURER ( MNAME ) );
CREATE TABLE CUSTOMER ( CNUM VARCHAR ( 25 ) NOT NULL,
CNAME VARCHAR ( 75 ) NOT NULL,
CTYPE VARCHAR ( 20 ) NOT NULL,
CONSTRAINT CUSTOMER_PKEY PRIMARY KEY ( CNUM ),
CONSTRAINT CHECK_CTYPE CHECK
( CTYPE IN ('INDIVIDUAL', 'INSTITUITION') ) );
CREATE TABLE ORDERS ( CNUM VARCHAR ( 25 ) NOT NULL,
PNUM VARCHAR ( 25 ) NOT NULL,
ORDERDATE DATE NOT NULL,
ORDERQUANTITY NUMBER ( 7, 2 ) NOT NULL,
CONSTRAINT ORDERS_PKEY PRIMARY KEY
( CNUM, PNUM, ORDERDATE ),
CONSTRAINT ORDERS_FKEY1 FOREIGN KEY
( CNUM )
REFERENCES CUSTOMER ( CNUM ),
CONSTRAINT ORDERS_FKEY2 FOREIGN KEY
( PNUM )
REFERENCES PART ( PNUM ) );
INSERT INTO
PART
VALUES
( 'S001',
'System-Economy',
1100,
NULL );
INSERT INTO
PART
VALUES
( 'M001',
'Monitor-17 inch',
250,
'S001' );

how to create interim table from (select * ) code in DBMS_REDEFINITION

I want to create Interim table from main table for DBMS_Redefinition Process.
but the requirement is not to write entire create syntax because there are n number of tables and i cant take each value every time.
INTERIM TABLE = table_INTER
MAIN_TABLE = table_MAIN
for eg..
CREATE TABLE table_INTER (
ContactPartKey NUMBER(20) NOT NULL,
PartyKey NUMBER(10) NOT NULL,
ConParticipationRoleKey NUMBER(10) NOT NULL,
ChannelKey NUMBER(10) NOT NULL,
StateKey NUMBER(10) NOT NULL,
StateReasonKey NUMBER(10) NOT NULL,
NextStateKey NUMBER(10) NOT NULL,
PreviousStateKey NUMBER(10) NOT NULL,
QueueKey NUMBER(10) NOT NULL,
RtgPointKey NUMBER(10) NOT NULL,
ContactPartIndKey NUMBER(10) NOT NULL,
DeviceKey NUMBER(10) NOT NULL,
ContactID NUMBER(20) NOT NULL,
Parent1ContactID NUMBER(20) ,
StartDateKey NUMBER(10) NOT NULL,
EndDateKey NUMBER(10) NOT NULL,
StartTimeKey NUMBER(3) NOT NULL,
EndTimeKey NUMBER(3) NOT NULL,
StartDateTime DATE NOT NULL,
EndDateTime DATE NOT NULL,
StateDur NUMBER(10) NOT NULL,
ContactAllocatedCost decimal(14,4) ,
ContactPartSeqNum NUMBER(10) NOT NULL,
ContactInProcessInd NUMBER(3) NOT NULL,
FinalPartInd NUMBER(3) NOT NULL,
Counter NUMBER(10) NOT NULL,
SourceKey NUMBER(10) NOT NULL,
StreamKey NUMBER(10) NOT NULL,
ProcessKey NUMBER(10) ,
SelfServiceInd NUMBER(3) )
--PRIMARY KEY(ContactPartKey)
TABLESPACE AVAYAIQFACT1
STORAGE (INITIAL 2097152 NEXT 2097152)
PCTFREE 0
PARTITION BY RANGE (STARTDATETIME)
INTERVAL(NUMTOYMINTERVAL(1, 'MONTH'))
(PARTITION P1 VALUES LESS THAN (TO_DATE('01/09/2013', 'DD/MM/YYYY')) TABLESPACE T1,
PARTITION P2 VALUES LESS THAN (TO_DATE('01/10/2013', 'DD/MM/YYYY')) TABLESPACE T1);
In above syntax, column name value cant be given every time. So what i did was
create table table_INTER as (select * from table_MAIN);
But can anyone tell me how to introduce partition in this interim table (table_INTER).
Can you try this?
CREATE TABLE TABLE_INTER
PARTITION BY RANGE (STARTDATETIME)
INTERVAL ( NUMTOYMINTERVAL ( 1,
'MONTH' ) )
( PARTITION P1
VALUES LESS THAN
(TO_DATE ( '01/09/2013',
'DD/MM/YYYY' ))
TABLESPACE T1,
PARTITION P2
VALUES LESS THAN
(TO_DATE ( '01/10/2013',
'DD/MM/YYYY' ))
TABLESPACE T1 )
AS
( SELECT * FROM TABLE_MAIN );