Percent revenue increase since previous year per country - sql-server

I need to get the percentage increase revenue since last year, per country.
create table Customer
(
customer_mail_address varchar(255) not null,
lastname varchar(50) not null,
firstname varchar(50) not null,
payment_method varchar(10) not null,
payment_card_number varchar(30) not null,
contract_type varchar(20) not null,
subscription_start date not null,
subscription_end date ,
user_name varchar(30) not null,
password varchar(50) not null,
country_name varchar(50) not null,
gender char(1) ,
birth_date date ,
constraint pk_Customer primary key(customer_mail_address),
constraint fk_Customer1 foreign key(country_name) references Country(country_name) ON UPDATE CASCADE,
constraint fk_Customer2 foreign key(contract_type) references Contract(contract_type) ON UPDATE CASCADE,
constraint fk_Customer3 foreign key(payment_method) references Payment(payment_method) ON UPDATE CASCADE,
constraint chk_Customer1 check(subscription_start < subscription_end),
constraint uc_Customer unique(user_name),
constraint chk_Customer2 check(len([password]) >= 8 AND [password] like '%[0-9]%'),
constraint chk_Customer3 check(birth_date < subscription_start),
constraint chk_Customer4 check(user_name NOT LIKE '%[^A-Z0-9]%')
)
create table Watchhistory
(
movie_id integer not null,
customer_mail_address varchar(255)not null,
watch_date date not null,
price numeric(5,2)not null,
invoiced bit not null,
constraint pk_Watchhistory primary key(movie_id, customer_mail_address, watch_date),
constraint fk_Watchhistory1 foreign key(movie_id) references Movie(movie_id),
constraint fk_Watchhistory2 foreign key(customer_mail_address) references Customer(customer_mail_address) ON UPDATE CASCADE ON DELETE CASCADE
)
These two tables are what I use to calculate this. I tried a lot of stuff but nothing really did the trick. This is what I have now to calculate the revenue for each year per country but not the percentage increase per country.
CREATE VIEW OmzetStijgingDalingPerLand AS
SELECT DATEPART(yy,watch_date) as [jaar], country_name, SUM(price) AS [omzet]
FROM Watchhistory w
INNER JOIN Customer c ON w.customer_mail_address = c.customer_mail_address
GROUP BY DATEPART(yy,watch_date), country_name

As it is described in article mentioned before, LAG function is the key
SELECT jaar,
country_name,
omzet,
omzet / LAG(omzet, 1) OVER(PARTITION BY country_name ORDER BY jaar) AS increase_percent
FROM OmzetStijgingDalingPerLand

Related

How can I reference 2 different columns in 2 different tables simultaneously

This is an assignment and I have been given this diagram for reference - https://imgur.com/gallery/wRkArmQ
There are other tables that I will include but the issue seems to be with the tables section and time_slot. In the diagram, they reference each other but I don't know how to. Any comments are helpful! I am using Oracle btw, here is the code -
create table department (
dept_name varchar(15) primary key,
building varchar(10),
budget int
);
create table instructor (
id varchar(10) primary key,
name varchar(15) not null,
dept_name varchar(20) not null
references department(dept_name) on delete cascade,
salary int not null
);
create table course (
course_id varchar(10) primary key,
title varchar(10),
dept_name varchar(15)
references department(dept_name) on delete cascade,
credits int
);
create table classroom (
building varchar(10) not null,
room_no varchar(5) not null,
capacity int not null,
primary key (building, room_no)
);
create table section (
course_id varchar(10) not null
references course(course_id),
sec_id varchar(10) not null,
semester varchar(10) not null,
year varchar(10) not null,
building varchar(10) not null
references classroom(building),
room_no varchar(5) not null
references classroom(room_no),
time_slot_id varchar(5) not null
references time_slot(time_slot_id),
primary key (course_id, sec_id, semester, year)
);
create table time_slot (
time_slot_id varchar(5) not null
references section(time_slot_id),
day varchar(10) not null,
start_time date not null,
end_time date not null,
primary key (time_slot_id, day, start_time)
);
create table teaches (
id varchar(10) primary key
references instructor(id) on delete cascade,
course_id varchar(15) not null
references section(course_id),
sec_id varchar(5) not null
references section(sec_id),
semester varchar(15)
references section(semester),
year int not null
references section(year)
);
create table student (
id varchar(10) not null primary key,
name varchar(20) not null,
dept_name varchar(15) not null
references department(dept_name) on delete cascade,
tot_cred int not null
);
create table advisor (
s_id varchar(10) primary key
references student(id) on delete cascade,
i_id varchar(6)
references instructor(id) on delete cascade
);
create table prereq (
course_id varchar(10)
references course(course_id) on delete cascade,
prereq_id varchar(10)
references course(course_id) on delete cascade,
primary key (course_id, prereq_id)
);
create table takes (
id varchar(10) not null
references student(id) on delete cascade,
course_id varchar(10) not null
references section(course_id) on delete cascade,
sec_id varchar(10) not null
references section(sec_id) on delete cascade,
semester varchar(10) not null
references section(semester) on delete cascade,
year int not null
references section(year) on delete cascade,
grade varchar(10) not null,
primary key (id, course_id, sec_id, semester, year, grade)
);
This is the output -
Table created.
Table created.
Table created.
Table created.
ORA-02270: no matching unique or primary key for this column-list
ORA-00942: table or view does not exist
ORA-00942: table or view does not exist

Postgresql Trying to implement One-To-Many

this is my first hands-on experience with Sql and I'm trying to construct One-To-Many relationship, here is the SQL code:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL,
cars_owning INT[] REFERENCES car(id)
);
and I get this error:
Key columns "cars_owning" and "id" are of incompatible types: integer[] and integer.
Here is the model a person can have many cars but each car have only one owner
typically (as a good general rule of thumb) the many refers to the one. not the other way around as you have tried.
So, alter the schema as:
create table car (
id SERIAL PRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL,
owner_id BIGINT FOREIGN KEY REFERENCES person(id)
);
create table person (
id BIGSERIAL NOT NULL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender VARCHAR(7) NOT NULL,
email VARCHAR(100),
date_of_birth DATE NOT NULL,
country_of_birth VARCHAR(50) NOT NULL
);
If you need to get the list of cars owned by a person, use this select statement
SELECT person.id, ARRAY_AGG(car.id) owns_car_ids
FROM person
LEFT JOIN car ON person.id = car.owner_id
GROUP BY 1

Foreign key reference mismatched data type error

The ArtistID column in Piece table refers to the ArtistID in the Artist table. Likewise, the LocationID column in Piece refers to LocationID in the GeographicLocation table. However, both foreign key references throw a "not the same data type as referencing column" error. What am I doing wrong?
CREATE TABLE dbo.Artist
(
ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Sex CHAR(1) NOT NULL CHECK(Sex = 'F' OR Sex = 'M')
)
CREATE TABLE dbo.Piece
(
PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Artist(ArtistID),
LocationID SMALLINT NOT NULL
FOREIGN KEY REFERENCES GeographicLocation(LocationID),
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL
FOREIGN KEY REFERENCES Appraiser(AppraiserID)
)
CREATE TABLE dbo.GeographicLocation
(
LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL
)
I think you missed a table here, which is AppraiserID column in Piece table refers to the AppraiserID in the Appraisertable
So, when I execute your SQL I am getting below error:
Foreign key 'FK__Piece__Appraiser__322C6448' references invalid table 'Appraiser'.
First Create a table called Appraiser, then create Foreign key references for those column.
Below SQL I am able to create all tables and Foreign key references:
CREATE TABLE dbo.Artist
(ArtistID SMALLINT PRIMARY KEY IDENTITY,
LastName VARCHAR(50) NOT NULL,
FirstName VARCHAR(40) NOT NULL,
Nationality VARCHAR(10) NULL,
BirthYear SMALLINT NOT NULL CHECK(BirthYear <= 1980),
DeathYear SMALLINT NULL,
Gender CHAR(1) NOT NULL CHECK(Gender = 'F' OR Gender = 'M'))
CREATE TABLE dbo.GeographicLocation
(LocationID SMALLINT PRIMARY KEY IDENTITY,
Country VARCHAR(25) NOT NULL,
City VARCHAR(50) NOT NULL)
CREATE TABLE dbo.Appraiser
(AppraiserID SMALLINT PRIMARY KEY IDENTITY(1, 5),
AppraisedValue MONEY NOT NULL,
AppraisedName VARCHAR(100) NULL)
CREATE TABLE dbo.Piece
(PieceID SMALLINT PRIMARY KEY IDENTITY(1, 5),
ArtistID SMALLINT NOT NULL,
LocationID SMALLINT NOT NULL,
CommonName VARCHAR(100) NULL,
YearProduced TINYINT NULL,
Period VARCHAR(50) NULL,
Medium VARCHAR(35) NOT NULL,
Frame VARCHAR(35) NULL,
AppraisedValue MONEY NOT NULL,
AppraiserID SMALLINT NOT NULL)
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_ArtistID FOREIGN KEY(ArtistID)
REFERENCES dbo.Artist (ArtistID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_ArtistID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_AppraiserID FOREIGN KEY(AppraiserID)
REFERENCES dbo.Appraiser (AppraiserID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_AppraiserID
GO
ALTER TABLE dbo.Piece WITH CHECK ADD CONSTRAINT FK_Piece_LocationID FOREIGN KEY(LocationID)
REFERENCES dbo.GeographicLocation (LocationID)
GO
ALTER TABLE dbo.Piece CHECK CONSTRAINT FK_Piece_LocationID
GO

Insert new record with composite primary key, which consists of two foreign keys from different tables

Please help me figure out how to Insert new record with composite primary key, which consists of two foreign keys from different tables.
I am working in C#, WPF if that matters.
I have three tables: Sales, SaleItem, Item.
CREATE TABLE [dbo].[Sales] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[saleTime] DATETIME NOT NULL,
[customerID] INT NULL,
[TIN] INT NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED ([saleID] ASC),
CONSTRAINT [FK_Sales_Customers] FOREIGN KEY ([customerID]) REFERENCES [dbo].[Customers] ([customerID]),
CONSTRAINT [FK_Sales_Company] FOREIGN KEY ([TIN]) REFERENCES [dbo].[Company] ([TIN])
);
CREATE TABLE [dbo].[Item] (
[ItemSKU] INT IDENTITY (1, 1) NOT NULL,
[itemName] NVARCHAR (50) NOT NULL,
[volume] FLOAT (53) NOT NULL,
[measureUnit] NVARCHAR (50) NOT NULL,
[producer] NVARCHAR (50) NOT NULL,
[supplierID] INT NOT NULL,
[retailPrice] NUMERIC (18) NOT NULL,
CONSTRAINT [PK_Item] PRIMARY KEY CLUSTERED ([ItemSKU] ASC),
CONSTRAINT [FK_Item_Suppliers] FOREIGN KEY ([supplierID]) REFERENCES [dbo].[Suppliers] ([supplierID])
);
CREATE TABLE [dbo].[SaleItem] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[itemSKU] INT NOT NULL,
[quantity] INT NOT NULL,
CONSTRAINT [PK_SaleItem] PRIMARY KEY CLUSTERED ([saleID] ASC, [itemSKU] ASC),
CONSTRAINT [FK_SaleItem_Sales] FOREIGN KEY ([saleID]) REFERENCES [dbo].[Sales] ([saleID]),
CONSTRAINT [FK_SaleItem_Item] FOREIGN KEY ([itemSKU]) REFERENCES [dbo].[Item] ([ItemSKU])
);
I want to insert a new record into SaleItem table (the third one) where saleID is the last ID recorded in Sales table and ItemSKU which is equal to the value I get from another window.
I want these values:
SaleID = SELECT TOP 1 saleID FROM Sales ORDER BY saleID DESC";
ItemSKU = "SELECT itemName FROM Item WHERE ItemSKU = #sku";
I think I must do it in one query but I have no idea how.
Can you please give me a hint? I
First, you need to remove the IDENTITY property from the dbo.SaleItem table. The IDENTITY property is only required on the parent table, dbo.Sales.
You can do a single INSERT statement like this. It uses two subqueries, which are the SELECT statements in parentheses, to get values from the other two tables.
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = N'Widget'),
50);
You might want to turn it into a stored procedure, like this:
CREATE PROCEDURE dbo.up_InsertSaleItem
(
#itemName nvarchar(50),
#quantity int
)
AS
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = #itemName),
#quantity);
Then to use the stored procedure:
-- Test the stored procedure
EXEC dbo.up_InsertSaleItem #itemName=N'Widget', #quantity=50;
SELECT *
FROM dbo.SaleItem;
To read more about subqueries, see Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan, Chapter 4: Subqueries.

Oracle create table Invalid Name / Constraint

I met an error in an SQL command when trying to create a table in SQL. Below is my command:
CREATE TABLE Registration
(
registrationID varchar2(5) NOT NULL CONSTRAINT registrationID PRIMARY KEY,
competitionID varchar2(5) NOT NULL CONSTRAINT competitionID REFERENCES Competition(competitionID),
competitorID varchar2(5) NOT NULL CONSTRAINT competitorID REFERENCES Competitor(competitorID),
categoryType varchar2(6) NOT NULL,
entryFeeStatus char(1) NOT NULL,
creditCardNumber number(16),
datePaid date
);
My competitionID is primary key of Competition table.
My competitorID is primary key of Competitor table.
The error shown is:
Error report -
SQL Error: ORA-02264: name already used by an existing constraint
02264. 00000 - "name already used by an existing constraint"
*Cause: The specified constraint name has to be unique.
*Action: Specify a unique constraint name for the constraint.
May I know what I should change in my statement? Thank you.
Below are the Competition and Competitor tables that I created:
CREATE TABLE Competition
(
competitionID varchar2(5) NOT NULL CONSTRAINT competitionID PRIMARY KEY,
timePlanned date NOT NULL,
country varchar2(50) NOT NULL,
city varchar2(50),
address varchar2(50),
entryFee number(4) NOT NULL
);
CREATE TABLE Competitor
(
competitorID varchar2(5) NOT NULL CONSTRAINT competitorID PRIMARY KEY,
firstName varchar2(9) NOT NULL,
lastName varchar2(9) NOT NULL,
dateOfBirth date NOT NULL,
nationality varchar2(12),
gender varchar2(1) NOT NULL,
lifetimeRanking number(6),
totalPrizeMoney number(6)
);
You mixed up the two different ways to specify foreign keys. And had an extra comma.
CREATE TABLE Registration
(
registrationID varchar2(5) NOT NULL CONSTRAINT registrationID PRIMARY KEY,
competitionID varchar2(5) NOT NULL CONSTRAINT competitionIDfk REFERENCES Competition(competitionID),
competitorID varchar2(5) NOT NULL CONSTRAINT competitorIDfk REFERENCES Competitor(competitorID)
)
Foreign keys can either be specified per column:
columnname datatype CONSTRAINT constraintname REFERENCES tablename [ (column) ]
Or per table:
CONSTRAINT constraintname FOREIGN KEY (column-list) REFERENCES tablename [ (column-list) ]
BOOLEAN is not valid SQL type. Use NUMBER(1) with 0 and 1, CHAR(1) or VARCHAR2(1) with 'Y' and 'N' values or other surrogate representation.

Resources