Query using analytic functions in postgresql - postgresql

I have the following tables in postgresql and I would like to make a query using analytical functions to obtain the following results: The name of the athlete, the discipline and the country, A column indicating the best time of the discipline. (REGISTER_MEASURE), A column containing the average time by country and discipline, A column containing the number of participations by country and discipline, A column containing the cumulative of the previous column (we will see at the end the number of participants in the discipline), The information must be sorted by discipline, country and athlete. All in a single output.
CREATE TABLE olympic.tb_discipline (
discipline_id INT NOT NULL,
name CHARACTER VARYING(50) NOT NULL,
inventor CHARACTER VARYING(50) NOT NULL,
type CHARACTER VARYING(10) NOT NULL,
object_type CHARACTER VARYING(20) DEFAULT NULL,
CONSTRAINT ck_discipline_type CHECK (type IN ('RUN', 'JUMP', 'THROW')),
CONSTRAINT pk_discipline PRIMARY KEY (discipline_id)
);
CREATE TABLE olympic.tb_athlete (
athlete_id CHARACTER(7) NOT NULL,
name CHARACTER VARYING(50) NOT NULL,
country CHARACTER VARYING(3) NOT NULL,
substitute_id CHARACTER(7) DEFAULT NULL,
CONSTRAINT pk_athlete PRIMARY KEY (athlete_id),
CONSTRAINT fk_athlete_substitute FOREIGN KEY (substitute_id) REFERENCES olympic.tb_athlete (athlete_id)
);
CREATE TABLE olympic.tb_play (
athlete_id CHARACTER(7) NOT NULL,
discipline_id INT NOT NULL,
CONSTRAINT pk_play PRIMARY KEY (athlete_id, discipline_id),
CONSTRAINT fk_play_athlete FOREIGN KEY (athlete_id) REFERENCES olympic.tb_athlete (athlete_id),
CONSTRAINT fk_play_discipline FOREIGN KEY (discipline_id) REFERENCES olympic.tb_discipline (discipline_id)
);
CREATE TABLE olympic.tb_round (
round_number INT NOT NULL,
discipline_id INT NOT NULL,
CONSTRAINT pk_round PRIMARY KEY (discipline_id, round_number),
CONSTRAINT fk_round_discipline FOREIGN KEY (discipline_id) REFERENCES olympic.tb_discipline (discipline_id)
);
CREATE TABLE olympic.tb_register (
athlete_id CHARACTER(7) NOT NULL,
round_number INT NOT NULL,
discipline_id INT NOT NULL,
register_date DATE NOT NULL DEFAULT CURRENT_DATE,
register_position INT DEFAULT NULL,
register_time TIME DEFAULT NULL,
register_measure REAL DEFAULT NULL,
CONSTRAINT pk_register PRIMARY KEY (athlete_id, round_number, discipline_id),
CONSTRAINT fk_register_athlete FOREIGN KEY (athlete_id) REFERENCES olympic.tb_athlete (athlete_id),
CONSTRAINT fk_register_round FOREIGN KEY (discipline_id, round_number) REFERENCES olympic.tb_round (discipline_id, round_number)
);
I have tried to implement the query similar to the following but I am not getting satisfactory results.
SELECT tb_athlete.name, tb_discipline.name
, tb_athlete.country
, MAX(tb_register.register_measure) OVER (PARTITION BY tb_discipline.name)
, AVG(tb_register.register_time) OVER (PARTITION BY tb_discipline.name)
FROM olympic.tb_athlete
JOIN olympic.tb_register USING (athlete_id)
JOIN olympic.tb_discipline USING (discipline_id);
Image sample
Could you help me with a solution. Thank you!

Related

What is wrong with this Query ? PostgreSQL

I want to create 3 tables and join them with foreign keys. Unfortunately, it doesn't work and I have no idea where is a mistake.
CREATE TABLE Students (
Student_Id SERIAL PRIMARY KEY,
Name VARCHAR (20) NOT NULL,
Surname VARCHAR (30) NOT NULL,
Date_of_Birth DATE NOT NULL,
Phone INT NOT NULL UNIQUE,
Email VARCHAR(225) NOT NULL UNIQUE,
Course_Id INT
FOREIGN KEY (Course_Id) REFERENCES Course (Course_Id)
);
CREATE TABLE Course (
Course_Id SERIAL PRIMARY KEY,
Student_Id INT NOT NULL,
Teacher_Id INT NOT NULL,
Category VARCHAR (30) NOT NULL,
FOREIGN KEY (Student_Id) REFERENCES Students (Student_Id)
);
CREATE TABLE Teachers (
Teacher_Id SERIAL PRIMARY KEY,
Name VARCHAR (20) NOT NULL,
Surname VARCHAR (30) NOT NULL,
Phone INT NOT NULL UNIQUE,
Salary INT NOT NULL,
Course_Id INT NOT NULL,
FOREIGN KEY (Teacher_Id) REFERENCES Course (Teacher_Id)
);
I should create a Foreign Key to join all three tables.
I get this error every time: relation "course" does not exist
I can't find where is the mistake. Please help.
It appears like you are attempting to crate a many-to-many (M:M) between Students and Teachers with Course as the resolution table. You are close, however, your definition sets up bi-directional relationships. This is normally not necessary. Define Students and Teachers without the FK to Course. Then define Course with a FK to each.
create table students (
student_id serial primary key
, name varchar (20) not null
, surname varchar (30) not null
, date_of_birth date not null
, phone int not null unique
, email varchar(225) not null unique
);
create table teachers (
teacher_id serial primary key
, name varchar (20) not null
, surname varchar (30) not null
, phone int not null unique
, salary int not null
);
create table course (
course_id serial primary key
, student_id int not null
, teacher_id int not null
, category varchar (30) not null
, foreign key (student_id) references students (student_id)
, foreign key (teacher_id) references teachers (teacher_id)
, unique (student_id, teacher_id)
);
If you must define bi-directional FK in Students and Teachers then create the tables without the FK then use alter table after Course is defined to add the FK and make them DEFERRABLE INITIALLY DEFERRED. Necessary for eventual Inserts.
alter table teachers add column course_id int references course(course_id) deferrable initially deferred;
alter table students add column course_id int references course(course_id) deferrable initially deferred;

Postgres Update Query

I'm executing below query in postgres 12.11
Table structure as below:
CREATE TABLE pdb_interface.schedule (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
report varchar NOT NULL,
users varchar NOT NULL,
"hour" int4 NULL,
min int4 NULL,
daily_frequency int4 NULL,
daily_workday bool NULL,
weekly_frequency int4 NULL,
weekly_days varchar NULL,
monthly_sected_days varchar NULL,
last_updated timestamp NULL,
deleted bool NULL,
CONSTRAINT schedule_pkey PRIMARY KEY (id),
CONSTRAINT schedule_report_fkey FOREIGN KEY (report) REFERENCES pdb_interface.report("Id"),
CONSTRAINT schedule_users_fkey FOREIGN KEY (users) REFERENCES pdb_interface.users("Id"));
update schedule
set daily_frequency = 12
where id = 'f2f0ba60-f8b1-49ae-a82c-aaddb1a1834b'
The column "id" is of uuid and value is present in the table . However while executing above query, it is giving below error
SQL Error [XX000]: ERROR: no conversion function from character varying to uuid
Is there any work around for the same

PostgreSQL gives syntax error at "foreign" or near

These are tables before referances
CREATE TABLE olap.time (
idtime SERIAL NOT NULL PRIMARY KEY,
year integer,
month integer,
week integer,
day integer
);
CREATE TABLE olap.addressees (
idaddressee integer PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(60) NOT NULL
);
CREATE TABLE olap.customers (
idcustomer varchar(10) SERIAL PRIMARY KEY autoincrement,
name varchar(40) NOT NULL,
city varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(40) NOT NULL,
email varchar(40),
phone varchar(16) NOT NULL,
regon char(9)
);
After creating this tables I want to create this table
CREATE TABLE olap.fact(
idtime integer NOT NULL,
idaddressee integer NOT NULL,
idcustomer varchar(10) NOT NULL,
idfact integer NOT NULL,
price numeric(7,2),
PRIMARY KEY (idtime, idaddressee, idcustomer),
FOREIGN KEY (idaddressee) REFERENCES olap.addressees(idaddressee),
FOREIGN KEY (idcustomer REFERENCES olap.customers(idcustomer),
FOREIGN KEY (idtime) REFERENCES time(idtime)
));
But I get error as
"ERROR: syntax error at or near "REFERENCES"
LINE 9: FOREIGN KEY (idcustomer REFERENCES olap.customers(idcustom..."
Thanks in advance
The idcustomer from olap.fact and idcustomer from olap.customers has different datatype SERIAL and Varchar(10),
I have corrected the datatypes and validated the code below
CREATE TABLE olap.time (
idtime SERIAL NOT NULL PRIMARY KEY,
year integer,
month integer,
week integer,
day integer
);
CREATE TABLE olap.addressees (
idaddressee integer PRIMARY KEY NOT NULL,
name varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(60) NOT NULL
);
CREATE TABLE olap.customers (
idcustomer varchar(10) PRIMARY KEY ,
name varchar(40) NOT NULL,
city varchar(40) NOT NULL,
zip char(6) NOT NULL,
address varchar(40) NOT NULL,
email varchar(40),
phone varchar(16) NOT NULL,
regon char(9)
);
CREATE TABLE olap.fact(
idtime integer NOT NULL,
idaddressee integer NOT NULL,
idcustomer varchar(10) NOT NULL,
idfact integer NOT NULL,
price numeric(7,2),
PRIMARY KEY (idtime, idaddressee, idcustomer),
FOREIGN KEY (idaddressee) REFERENCES olap.addressees(idaddressee),
FOREIGN KEY (idcustomer) REFERENCES olap.customers(idcustomer),
FOREIGN KEY (idtime) REFERENCES olap.time(idtime)
);

CREATE Statement in PostgreSQL error relation does not exist

My question is similar to the one posted earlier in the Community. questions/62936399/error-sql-state-42703-while-trying-to-insert-data-into-my-table
In PostgreSQL, I'm trying to run CREATE Table Statement so that I can continue with inserting values. Although my CREATE statement fails so I can't get on with INSERT statement. The error message that keeps coming up ERROR: relation "eventrequest" does not exist
SQL state: 42P01
I have re-did the entire CREATE Statement twice although the error message does not change.
CREATE TABLE CUSTOMER
(CustNo VARCHAR(8) CONSTRAINT CustNoNotNull NOT NULL,
CustName VARCHAR(30) CONSTRAINT CustNameNotNull NOT NULL,
Address VARCHAR(50) CONSTRAINT AddressNotNull NOT NULL,
Internal CHAR(1) CONSTRAINT InternalNotNull NOT NULL,
Contact VARCHAR(35) CONSTRAINT ContractNotNull NOT NULL,
Phone VARCHAR(11) CONSTRAINT CPhoneNotNull NOT NULL,
City VARCHAR(30) CONSTRAINT CityNotNull NOT NULL,
State VARCHAR(2) CONSTRAINT StateNotNull NOT NULL,
Zip VARCHAR(10) CONSTRAINT ZipNotNull NOT NULL,
CONSTRAINT PK_CUSTOMER PRIMARY KEY (CustNo)
);
CREATE TABLE FACILITY
(FacNo VARCHAR(8) CONSTRAINT FacNoNotNull NOT NULL,
FacName VARCHAR(30) CONSTRAINT FacNameNotNull NOT NULL,
CONSTRAINT PK_FACILITY PRIMARY KEY (FacNo),
CONSTRAINT Unique_FacName UNIQUE(FacName)
);
CREATE TABLE LOCATION
(LocNo VARCHAR(8) CONSTRAINT LocNoNotNull NOT NULL,
FacNo VARCHAR(8),
LocName VARCHAR(30) CONSTRAINT LocNameNotNull NOT NULL,
CONSTRAINT PK_LOCATION PRIMARY KEY (LocNo),
CONSTRAINT FK_FACNO FOREIGN KEY (FacNo) REFERENCES FACILITY (FacNo)
);
CREATE TABLE EMPLOYEE
(
EmpNo CHAR(11) CONSTRAINT EmpNoNotNull NOT NULL,
EmpName VARCHAR(30) CONSTRAINT EmpNameNotNull NOT NULL,
Department VARCHAR(30) CONSTRAINT DepartmentNotNull NOT NULL,
Email VARCHAR(255) CONSTRAINT EmailNotNull NOT NULL,
Phone VARCHAR(30) CONSTRAINT PhoneNotNull NOT NULL,
CONSTRAINT PK_EMPLOYEE PRIMARY KEY (EmpNo)
);
CREATE TABLE EVENTPLAN
(
PlanNo VARCHAR(8) NOT NULL,
EventNo VARCHAR(8) NOT NULL,
workdate DATE NOT NULL,
notes VARCHAR(40),
activity VARCHAR(20) NOT NULL,
empno VARCHAR(8),
CONSTRAINT PK_PLANNO PRIMARY KEY (PlanNo),
CONSTRAINT FK_EVENTNO FOREIGN KEY (EventNo) REFERENCES EventRequest (EventNo)
);
CREATE TABLE EVENTREQUEST
(
EventNo VARCHAR(8) NOT NULL,
DateHeld DATE NOT NULL,
DateReq DATE NOT NULL,
FacNo VARCHAR(8) NOT NULL,
CustNo VARCHAR(8) NOT NULL,
DateAuth DATE,
Status VARCHAR(8) NOT NULL CHECK (Status IN ('Pending', 'Denied', 'Approved')),
EstCost DECIMAL(10, 2) NOT NULL,
EstAudience INT NOT NULL CHECK (EstAudience > 0),
BudNo VARCHAR(8),
CONSTRAINT PK_EVENTNO PRIMARY KEY (EventNo),
CONSTRAINT FK_FACILITYNOEVENTREQ FOREIGN KEY (FacNo) REFERENCES Facility (FacNo),
CONSTRAINT FK_CUSTOMERNO FOREIGN KEY (CustNo) REFERENCES Customer (CustNo)
);
CREATE TABLE EVENTPLANLINE
(
PlanNo CHAR(8) NOT NULL,
LineNo CHAR(8) NOT NULL,
LocNo CHAR(8) NOT NULL,
ResNo CHAR(8) NOT NULL,
TimeStart TIMESTAMP NOT NULL,
TimeEnd TIMESTAMP NOT NULL,
NumberFLD INTEGER NOT NULL,
CONSTRAINT PK_EVENTPLANLINE PRIMARY KEY (PlanNo, LineNo),
CONSTRAINT FK_EVENTPLAN FOREIGN KEY (PlanNo) REFERENCES EventPlan (PlanNo),
CONSTRAINT FK_LOCATION FOREIGN KEY (LocNo) REFERENCES Location (LocNo),
CONSTRAINT FK_RESOURCETBL FOREIGN KEY (ResNo) REFERENCES ResourceTbl (ResNo)
);
CREATE TABLE RESOURCETBL
(
ResNo CHAR(8) NOT NULL,
ResName VARCHAR(30) NOT NULL,
Rate DECIMAL(8, 2) NOT NULL,
CONSTRAINT PK_RESOURCETBL PRIMARY KEY (ResNo)
);

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'questions_ibfk_1' in the referenced table 'category'

cannot add foreign key constraint to table
create table users
(
user_id int auto_increment primary key not null,
username varchar(50) unique null ,
email varchar(50) unique ,
passwords varchar(50) not null,
login_status boolean not null
);
create table category (
category_id int primary key not null,
category_name varchar(50) not null
);
create table answers (
id_answer int auto_increment primary key not null,
answer boolean not null
);
create table questions (
question_id int primary key not null,
category_name varchar(50) not null,
content varchar(50) not null ,
foreign key (category_name) references category (category_name)
);
You get this error because there's no index on category_name in the category table. Change that CREATE statement as follows:
create table category (
category_id int primary key not null,
category_name varchar(50) not null,
KEY category_name_index (category_name)
);
From the docs (8.0 version, but the statement is true for older versions):
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Also, you're using a varchar(50) as your foreign key, which is not usually a great idea for a variety of reasons. You probably want to use a numeric value, such as category_id, instead.