Creating a view between two tables in SQL - sql

I'm having trouble creating a view between two tables, as I'm quite new to SQL. I need to create a view which will show which employees have carried out work as consultants within the past 14 days. The result of the view should also display this kind of layout:
14 day consultancy report
-----------------------------------------------
Employee Helvin Paul worked for 6 hours for factory ltd chargeable £351
The two tables I assume you will need to join together are the Employee table and also the Consultancy table. I will show both below as I have them in a text file from when I was creating these tables:
create table Funtom_employee
(
emp_ID Number(3) primary key,
Emp_firstname varchar2(50) not null,
Emp_surname varchar2(50),
Emp_department Number(2) constraint FK_funtom_dept references
funtom_department,
emp_street varchar2(50),
emp_town varchar2(50),
emp_district varchar2(50),
Emp_grade Number(3) default 4 constraint chk_emp_grd check (Emp_grade between 1 and 9),
Emp_site varchar2(30) default 'LONDON',
constraint FK_funtom_grade funtom_grade references funtom_department
);
create table Funtom_consultancy
(
consultancy_ID Number(3) primary key,
Consultancy_emp Number(3) constraint cns_emp references funtom_employee,
Consultancy_hours Number(4,2) constraint consultancy_check check (Consultancy_hours > 1),
Consultancy_client Number(3) references funtom_customer,
Consultancy_date DATE,
Consultancy_activity Number(3) references funtom_activity
);
Thanks to anyone that can help with this create view and for your time

A view can be created using the CREATE VIEW statement. An example based on your data is listed below.
CREATE VIEW consultancy_report as
select
Funtom_employee.Emp_firstname,
Funtom_consultancy.Consultancy_date,
from
Funtom_employee
join Funtom_consultancy
on Funtom_employee.emp_id = Funtom_consultancy.Consultancy_emp
You can add whatever other fields you need from either table in the select clause of the query. I've demonstrated one field from both tables.
If you want output explicitly as listed in your sample, you will need to concatenate several fields together as one string. Since this feels like a homework question, I will leave that as an exercise for you.

Related

I am trying to VIEW 4 columns from 2 different tables I have already created in Oracle Live SQL

I want to use the VIEW command to display these 4 columns in one single schema. I have tried making a single VIEW with the first 3 columns, because they are from the the same table. Adding the one other column is where I'm struggling. I have tried the ALTER function but a VIEW schema doesn't seem to have the same edit privileges as a table would. I hope that makes sense.
create table PATIENTINFO (
PatientID number not null,
FirstName varchar2(50) not null,
LastName varchar2(50) not null,
Address varchar2(50),
City varchar2(50),
State varchar2(50),
ZipCode number(5),
Phone number(10) not null ,
Email varchar2(50),
MemberID number not null,
constraint pk_departments primary key (PatientID)
)
create table LABORDER (
LabOrderNumber number not null,
OrDate date not null,
ReqBloodTest varchar2(15) not null,
Reason varchar(50),
PatientID number not null,
constraint pk_laborder primary key (LabOrderNumber),
constraint fk_laborder_patientid foreign key (PatientID)
references PATIENTINFO (PatientID)
)
CREATE VIEW PatientBlood AS
SELECT FirstName, LastName, PatientID
FROM PATIENTINFO
Write the query you want and then create a view out of it. I started by writing the query below and then prefixed it with CREATE OR REPLACE VIEW. The example below has some randomly selected columns, change it to whatever columns you need. I chose to name my columns in the view definition, you can omit that but also do a million other things as stated in the docs
Side note: don't use mixed case for identifiers like column names/table names. It is confusing. In your case it didn't matter since you didn't use quotes, so they're case insensitive and the view below will work even though the identifiers are all lower case.
CREATE OR REPLACE VIEW laborder_v (
labordernumber,
patientid,
lastname
) AS
SELECT o.labordernumber,
p.patientid,
p.lastname
FROM laborder o
JOIN patientinfo p ON o.patientid = p.patientid;

Why can't I see inserted data in my view / tables

Firstly I created a table like this:
CREATE TABLE "DEPTT_DEMO1"
(
"DEPARTMENT_ID" NUMBER(4,0),
"DEPARTMENT_NAME" VARCHAR2(30 BYTE) CONSTRAINT "DEPT_NAME_NN1" NOT NULL ENABLE,
"MANAGER_ID" NUMBER(6,0),
"LOCATION_ID" NUMBER(4,0),
CONSTRAINT "DEPT_ID_PK1" PRIMARY KEY ("DEPARTMENT_ID")
);
After the table is created, I insert a few rows of data and then created a view like this:
CREATE OR REPLACE VIEW dept_demo_vw1
AS
SELECT DEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID
FROM DEPTT_DEMO1;
I create a trigger as well:
CREATE OR REPLACE TRIGGER vw_dept_tri
INSTEAD OF INSERT ON dept_demo_vw1
--declare
BEGIN
UPDATE dept_demo_vw1
SET DEPARTMENT_ID = dept_id.nextval
WHERE DEPARTMENT_ID IS NULL;
END vw_dept_tri;
After this when I try to insert data into the view, it says that the data is inserted, but I can't see any data in my view.
I don't know what you are doing, but you're doing it wrong.
INSTEAD OF trigger you wrote doesn't make much sense. It is instead of INSERT, but you are performing an UPDATE
Moreover, you are updating a view, but you should have been doing it on a table (not a view); that's why it is called "instead of" - instead of inserting into a view, you'd be inserting into a table
DEPTT_DEMO1.DEPARTMENT_ID is a primary key column. It means that it can not accept NULL values
Trigger's WHERE clause says WHERE DEPARTMENT_ID IS NULL; it is never NULL, that's a primary key column
Shortly, you'll have to think it over and do it properly.

No row selected

SQL> create table artwork
2 (
artwork_id number(7) NOT NULL,
barcode char(20),
title char(20),
description char(50),
PRIMARY KEY (artwork_id)
);
Table created.
SQL> select * from artwork;
no rows selected
I created the table but it showing me this error dont know. Why table it not showing?
I would expect the create to look like this:
create table artwork (
artwork_id number primary key,
barcode char(20),
title varchar2(20),
description varchar2(50)
);
Notes:
There is no need to have number(7). You can specify the length, but it is not necessary.
For title and description you definitely want varchar2(). There is no reason to store trailing spaces at the end of a name.
That may be the same for barcode, but because it might always be exactly 20 characters or trailing spaces might be significant, you might leave it as char().
The primary key constraint can be expressed in-line. There is no need for a separate declaration.
You probably simply want something like
create table artwork
(
artwork_id number(7) NOT NULL,
barcode varchar2(20),
title varchar2(20),
description varchar2(50),
PRIMARY KEY (artwork_id)
);
insert into artwork values (0, 'barcode', 'fancytitle', 'somedescription');
insert into artwork values (1, 'barcode1', 'fancytitle1', 'somedescription1');
select * from artwork;
This creates a table "ARTWORK", inserts 2 rows in it and then selects all rows currently in the table.
An empty table contains no data, with the create table-statement you only define the bucket of data, you have to fill the bucket as well with items.
I'd also recommend a auto increment column (oracle 12c) or a trigger/sequence to increment the id automatically. But that's something to read later :)

Using joins in complex queries

I have three tables customer_cars, bookings, and replaced_parts ad below:
CREATE TABLE customer_cars(
pk_car_id NUMBER(11) NOT NULL,
car_plate_number VARCHAR2(15) NOT NULL
);
CREATE TABLE bookings(
pk_booking_id NUMBER(11),
fk_car_id NUMBER(11),
);
CREATE TABLE replaced_parts(
pk_parts_id VARCHAR2(25),
fk_booking_id NUMBER(11),
replaced_parts parts_varray_type
);
CREATE OR REPLACE TYPE parts_type AS OBJECT (
name VARCHAR2(25),
price NUMBER(10),
);
/
CREATE TYPE parts_varray_type AS
VARRAY(40) OF parts_type;
/
I am trying to get parts name from parts_varray_type of a car. All i have is car_plate_number. Using this plate number i want to find pk_car_id in customer_cars and then that pk_car_if id should match with fk_car_id in bookings to find bookings_id. Then the found booking id should match with fk_booking_id in replaced_parts to get the parts_name.
INSERT INTO customer_cars (pk_car_id, car_plate_number)
VALUES(200000,'5651L');
INSERT INTO bookings(pk_booking_id, fk_car_id)
VALUES(700000,200000);
INSERT INTO replaced_parts (pk_parts_id, fk_booking_id, replaced_parts)
VALUES(700000,600000,
parts_varray_type(
parts_type('CLUTCH', 2000)));
Above is the insert statements. Now using plate number '5651L' i want to display clutch , 2000 from parts parray type.
Something like:
SELECT..
FROM..(Usings joins or any other methods)
WHERE pk_car_id = '5651L';
It should display name and price from parts varray type.

SQL database design advice needed

My Database:
CREATE DATABASE `cars` /*!40100 DEFAULT CHARACTER SET latin1 */;
DROP TABLE IF EXISTS `cars`.`employees`;
CREATE TABLE `cars`.`employees` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(40) DEFAULT NULL,
`last_name` varchar(40) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
DROP TABLE IF EXISTS `cars`.`products`;
CREATE TABLE `cars`.`products` (
`prod_id` int(11) NOT NULL AUTO_INCREMENT,
`prod_name` varchar(40) DEFAULT NULL,
`prod_price` varchar(40) DEFAULT NULL,
PRIMARY KEY (`prod_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
That is my database query. I have task to create database of CARS which contains informations about employees and cars, also the database must contain information about which car is sold and which worker sold it.
My Question: How can I store a sale, so that I record which employee has sold which cars.
Possibly create a table for holding which employees sold which cars?
EmployeeSales
---------------
emp_id
prod_id
OtherInfo
This is a design decision that goes over the 1NF direction you ( or somebody else over your organization ) must considerate prior to development. To respond your concrete question, this is the typical case where a XRef table is needed to put together all the Customer-Vehicle associations along with extra details refered to the solds.
Ie:
Sale table:
-----------------------------
sale_id autonumeric(1,1) PK
, emp_id int FK
, prod_id int FK
, price decimal(10,2)
, sold_date datetime(2)
, other_interesting_sale_details
This is one possible solution that will keep historical info about which car was sold by a specific employee plus additional details it may be of interest for the particular business.
I hope it helps.
depends on how expansive you want to go... you have a products table... will this be it for your cars and every car will just be added to this directly? If so, then you could just tack on two fields
In the products table, add a column "SoldBy" as integer. This could be a link to the employees table Employee ID.
if the value is populated, it's sold, and if sold, it is the employee who sold it.