postgresql outer join query to get all data from one table - sql

I have two tables
CREATE TABLE REFERENCE_VALUES
(
REFERENCE_ID SERIAL,
REFERENCE_OBJ_NAME TEXT,
REFERENCE_VALUE_CODE BIGINT,
DISPLAY_NAME TEXT,
CREATED_ON TIMESTAMP,
MODIFIED_ON TIMESTAMP
);
ALTER TABLE REFERENCE_VALUES
ADD PRIMARY KEY (ID);
ALTER TABLE REFERENCE_VALUES
ADD FOREIGN KEY (REFERENCE_VALUE_CODE)
REFERENCES CATEGORY(ID);
CREATE TABLE CATEGORY
(
ID BIGSERIAL NOT NULL,
CODE TEXT NOT NULL,
NAME TEXT NOT NULL,
PARENT_ID BIGINT,
PATH TEXT,
COMP_ID BIGINT,
CREATED_ON TIMESTAMP,
MODIFIED_ON TIMESTAMP,
);
ALTER TABLE CATEGORY
ADD PRIMARY KEY (ID);
ALTER TABLE CATEGORY
ADD FOREIGN KEY (COMP_ID)
REFERENCES COMPANY_ID(ID);
I have the display names as DISPLAY_NAME in REFERENCE_VALUES table I want to SELECT all values from table CATEGORY but the value of NAME (In CATEGORY table) replaced by value from DISPLAY_NAME in REFERENCE_VALUES and if the value of of DISPLAY_NAME is NULL OR EMPTY i would keep the value of NAME (CATEGORY table).
I have been able to do that with the query below
SELECT C.ID, C.CODE, COALESCE(R.DISPLAY_NAME, C.NAME) as NAME, C.PARENT_ID, C.PATH, C.COMP_ID, C.CREATED_ON, C.MODIFIED_ON
FROM CATEGORY C
LEFT JOIN REFERENCE_VALUES R
ON C.ID = R.REFERENCE_VALUE_CODE
WHERE R.REFERENCE_OBJ_NAME = 'CATEGORY';
but i am getting only two records. How can i get all the records from the category table?
sample data to populate the tables
INSERT INTO CATEGORY VALUES (1, 'CVB', 'COMM VEH', NULL, 'CVB', 1, '2016-05-13 15:50:19.985', NULL);
INSERT INTO CATEGORY VALUES (2, 'LVB', 'AUTO', NULL, 'LVB', 1, '2016-05-13 15:50:19.994', NULL);
INSERT INTO CATEGORY VALUES (3, 'INB', 'INF', NULL, 'INB', 1, '2016-05-13 15:50:19.997', NULL);
INSERT INTO CATEGORY VALUES (4, 'OHB', 'OFF', NULL, 'OHB', 1, '2016-05-13 15:50:20', NULL);
INSERT INTO CATEGORY VALUES (5, 'LUB', 'LUB', NULL, 'LUB', 1, '2016-05-13 15:50:20.002', NULL);
INSERT INTO CATEGORY VALUES (52, 'TRA', 'TIE', 32, 'CVB.HA.TRA', 1, '2016-05-13 15:51:32.605', NULL);
INSERT INTO CATEGORY VALUES (68, 'PF', 'PER', 42, 'LVB.LA.PF', 1, '2016-05-13 15:51:33.117', NULL);
INSERT INTO CATEGORY VALUES (73, 'CE', 'CAR', 32, 'CVB.HA.CE', 1, '2016-05-13 15:51:33.733', NULL);
INSERT INTO CATEGORY VALUES (74, 'KP', 'KP', 32, 'CVB.HA.KP', 1, '2016-05-13 15:51:33.958', NULL);
INSERT INTO CATEGORY VALUES (26, 'RP', 'RING', 11, 'OHB.OH.RP', 1, '2016-05-13 15:51:30.149', NULL);
INSERT INTO CATEGORY VALUES (47, 'CP', 'COMP', 9, 'CVB.CV.CP', 1, '2016-05-13 15:51:31.903', NULL);
INSERT INTO CATEGORY VALUES (48, 'TB', 'TUB', 9, 'CVB.CV.TB', 1, '2016-05-13 15:51:31.905', NULL);
INSERT INTO CATEGORY VALUES (18, 'FB', 'FILT', 11, 'OHB.OH.FB', 1, '2016-05-13 15:51:30.002', NULL);
INSERT INTO REFERENCE_VALUES (ID, REFERENCE_OBJ_NAME, REFERENCE_VALUE_CODE, DISPLAY_NAME) VALUES (1, 'CATEGORY', 6, INDU CHANGED);
INSERT INTO REFERENCE_VALUES (ID, REFERENCE_OBJ_NAME, REFERENCE_VALUE_CODE) VALUES (2, 'CATEGORY', 7);

The WHERE condition filters out rows where R.REFERENCE_OBJ_NAME is null, which is all rows for which there are no matching REFERENCE_VALUE.
Maybe what you are trying to do is only join REFERENCE_VALUES where REFERENCE_OBJ_NAME is 'CATEGORY'. If so you could do it like this:
SELECT C.ID, C.CODE, COALESCE(R.DISPLAY_NAME, C.NAME) as NAME, C.PARENT_ID, C.PATH, C.COMP_ID, C.CREATED_ON, C.MODIFIED_ON
FROM CATEGORY C
LEFT JOIN REFERENCE_VALUES R
ON R.REFERENCE_OBJ_NAME = 'CATEGORY' AND C.ID = R.REFERENCE_VALUE_CODE

Related

Get max id for each entry from another related table

I have 2 tables namely entry and entry_log whose schema is as below:
entry:
id NUMBER PRIMARY KEY
name VARCHAR2(100)
entry_log:
id NUMBER PRIMARY KEY
parent_id NUMBER NOT NULL --> constraint el FOREIGN KEY (parent_id) REFERENCES entry ( id )
user_id NUMBER NOT NULL --> constaint rl_uk FOREIGN KEY (user_id) REFERENCES user ( id )
Note: User is another table that I have.
For every row in entry table I can have multiple rows in the entry_log table, where entry log table actually holds parent_id and the user who made the modification to a row in entry table.
Basically, entry is the actual table and a row is inserted in the entry_log table every time a create or update occurs in the entry table.
I need to have a query such that it returns the following columns:
id from entry table
name from entry table
max(id) from entry_log table where parent_id in entry_log = id in entry table
I have the below query which works but I want to achieve this without having to use subquery to improve performance.
select max(log_id) as log_id from (
SELECT
entry_log.id log_id,
entry_log.parent_id
FROM
entry
INNER JOIN entry_log ON entry_log.parent_id = entry.id
) group by parent_id
)
SELECT
entry.id,
entry.name,
mif.log_id "MAX_ID",
FROM
entry
INNER JOIN entry_log ON entry_log.parent_id = entry.id
INNER JOIN max_id_finder mif ON mif.log_id = entry_log.id
WHERE 1=1
Is there any better way to achieve this without impacting performance?
Pl check if the following solution works for you:
select a.*, b.* from entry a
inner join (select id, max(p_id) as p_id, `name` from entry_log group by p_id) b
on a.id = b.p_id
Dataset used:
CREATE TABLE `entry` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
CREATE TABLE `entry_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`p_id` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_p_id` (`p_id`),
CONSTRAINT `fk_p_id` FOREIGN KEY (`p_id`) REFERENCES `entry` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
insert into entry values (1, "A1");
insert into entry values (2, "A2");
insert into entry values (3, "A3");
insert into entry values (4, "A4");
insert into entry values (5, "A5");
insert into entry values (6, "A6");
insert into entry values (7, "A7");
insert into entry values (8, "A8");
insert into entry_log values (1, 1, "P001");
insert into entry_log values (2, 2, "P002");
insert into entry_log values (3, 1, "P003");
insert into entry_log values (4, 2, "P004");
insert into entry_log values (5, 3, "P005");
insert into entry_log values (6, 1, "P006");
insert into entry_log values (7, 2, "P007");
insert into entry_log values (8, 5, "P008");
insert into entry_log values (9, 2, "P007");
insert into entry_log values (10, 4, "P008");
insert into entry_log values (11, 7, "P001");
insert into entry_log values (12, 8, "P002");
insert into entry_log values (13, 6, "P003");
insert into entry_log values (14, 6, "P004");
insert into entry_log values (15, 3, "P005");
insert into entry_log values (16, 7, "P006");
insert into entry_log values (17, 2, "P007");
insert into entry_log values (18, 5, "P008");
Thanks user1300830
The below query works perfectly.
SELECT
entry.id,
entry.name,
entry_log.log_id,
FROM
entry
INNER JOIN (SELECT max(id) as log_id, parent_id from entry_log group by parent_id) entry_log ON entry_log.parent_id = entry.id
WHERE 1=1

How to list total number of scholarships per department in SQL

I have 2 tables that look like this where I want to query how many scholarships (from Tuition table) each department (from Student table) has distributed:
I am thinking a join is necessary but am not sure how to do so.
Create tables
create table students (
sid int auto_increment primary key,
name varchar(100),
email varchar(100),
department varchar(100)
);
create table tutions (
id int auto_increment primary key,
sid int,
cost int,
scholarships int,
duedate timestamp default current_timestamp
);
Sample data
insert into students (name, email, department)
values
('John Doe', 'john#abc.xyz', 'B'),
('Jane Doe', 'jane#abc.xyz', 'A'),
('Jack Doe', 'jack#abc.xyz', 'C'),
('Jill Doe', 'jill#abc.xyz', 'B');
insert into tutions (sid, cost, scholarships)
values
(1, 1000, 2),
(2, 1000, 1),
(3, 1000, 7),
(4, 1000, 2);
Query (department-wise total scholarships)
SELECT department, sum(scholarships) as scholarships
FROM students s
JOIN tutions t ON s.sid = t.sid
GROUP BY department
Output
Running SQL Fiddle
Not sure It's something you want? And not sure scholarships is a number or name of scholarship? So I doubt it's a name as varchar string type.
### dummy record
CREATE TABLE students (
psu_id INTEGER PRIMARY KEY,
firstname VARCHAR NOT NULL,
lastname VARCHAR NOT NULL,
email VARCHAR NOT NULL,
department VARCHAR NOT NULL
);
CREATE TABLE tuition (
tuition_id INTEGER PRIMARY KEY,
student_id INTEGER NOT NULL,
semeter_cost INTEGER NOT NULL,
scholarships VARCHAR NOT NULL,
due_date DATE NOT NULL
);
INSERT INTO students VALUES (1, 'John', 'Hello', 'Jonh#email.com', 'Engineering');
INSERT INTO students VALUES (2, 'Bella', 'Fuzz', 'Bella#email.com', 'Computer');
INSERT INTO students VALUES (3, 'Sunny', 'World', 'Sunny#email.com', 'Science');
INSERT INTO tuition VALUES (1, 1, 4000, 'first_class_en', '2022-05-09' );
INSERT INTO tuition VALUES (2, 2, 3000, 'nobel', '2022-05-09' );
INSERT INTO tuition VALUES (3, 3, 5000, 'hackathon', '2022-05-09' );
INSERT INTO tuition VALUES (4, 1, 4500, 'second_class_en', '2022-05-09' );
-----------------
### query
SELECT s.department, count(t.scholarships)
FROM students s
JOIN tuition t
ON s.psu_id = t.student_id
GROUP BY s.department
### output
department, total_scholarships
Computer|1
Engineering|2
Science|1

find the common Class ID for a list of students

I try to get the class id from student and class_student tables using jpql.
I give a list of students of students like this ('name1', 'name2', 'name5'), then if this list was assign to class, then I will have the class ID (class id = 2).
Note: the list ist unique, that means this list is only in one class.
CREATE DATABASE test;
USE test;
CREATE TABLE CLASS
( ID BIGINT NOT NULL PRIMARY KEY,
NAME VARCHAR(255) NOT NULL
) CHARSET = utf8mb4;
CREATE TABLE STUDENT
( ID BIGINT NOT NULL PRIMARY KEY,
NAME VARCHAR(255) NOT NULL,
constraint UK_NAME
unique (NAME)
)CHARSET = utf8mb4;
CREATE TABLE CLASS_STUDENT
(ID BIGINT NOT NULL PRIMARY KEY,
CLASS_ID BIGINT NOT NULL,
STUDENT_ID BIGINT NOT NULL,
CONSTRAINT FK_STUDENT
FOREIGN KEY (STUDENT_ID) REFERENCES STUDENT (ID),
CONSTRAINT FK_CLASS
FOREIGN KEY (CLASS_ID) REFERENCES CLASS (ID)
)CHARSET = utf8mb4;
INSERT INTO CLASS (ID, name)
VALUES (1, 'class1'),
(2, 'class2'),
(3, 'class3');
INSERT INTO STUDENT (ID, name)
VALUES (1, 'name1'),
(2, 'name2'),
(3, 'name3'),
(4, 'name4'),
(5, 'name5');
INSERT INTO CLASS_STUDENT (ID, CLASS_ID, STUDENT_ID)
VALUES (1, 1, 1),
(2, 1, 2),
(3, 1, 3),
(4, 1, 4),
(5, 2, 1),
(6, 2, 3),
(7, 2, 5),
(8, 3, 1),
(9, 3, 3),
(10, 3, 4),
(11, 3, 5);
This is a relational division problem. You can use aggregation and a having clause for filtering.
select cs.class_id
from class_student cs
inner join student s on s.id = cs.student_id
where s.name in ('name1', 'name2', 'name3')
group by cs.class_id
having count(*) = 3
The join brings in the students of each class, and the where clause filters on the three students we are interested in. Then, we group by class, and retain groups that contain three rows (one per student).
Edit:
If you want classes that have these three students and no other, then:
select cs.class_id
from class_student cs
inner join student s on s.id = cs.student_id
where s.name in ('name1', 'name2', 'name3')
group by cs.class_id
having sum(case when s.name in ('name1', 'name2', 'name3') then 1 else 0 end) = 3
and sum(case when s.name not in ('name1', 'name2', 'name3') then 1 else 0 end) = 0

What is wrong with my queries?

All the code is correct but the queries (which are at the very bottom) don't seem to run. I checked on w3schools.com for more information, but it seems like there's nothing wrong with my code.
Can anyone take a look and explain?
--Drop tables--
DROP TABLE Job;
DROP TABLE Employee;
DROP TABLE Purchase;
DROP TABLE SoccerBall;
DROP TABLE Client;
--Create tables--
CREATE TABLE Client
(
ClientId INT NOT NULL,
ClientName VARCHAR(20) NOT NULL,
Street VARCHAR(20) NOT NULL,
City VARCHAR(20) NOT NULL,
ZipCode VARCHAR(5) NOT NULL,
Phone VARCHAR(15) NULL,
EmailAddr VARCHAR(50) NULL,
PRIMARY KEY(ClientId)
);
CREATE TABLE SoccerBall
(
BallId INT NOT NULL,
BallSize NUMBER(1) NOT NULL,
Color VARCHAR(20) NOT NULL,
Material VARCHAR(20) NOT NULL,
PRIMARY KEY(BallId)
);
CREATE TABLE Purchase
(
PurchaseId INT NOT NULL,
ClientId INT NOT NULL,
BallId INT NOT NULL,
PurchaseDate DATE NOT NULL,
PRIMARY KEY (PurchaseId),
FOREIGN KEY (ClientId) REFERENCES Client (ClientId),
FOREIGN KEY (BallId) REFERENCES SoccerBall (BallId)
);
CREATE TABLE Employee
(
EmployeeId INT NOT NULL,
EmployeeName VARCHAR(50) NOT NULL,
PRIMARY KEY (EmployeeId)
);
CREATE TABLE Job
(
JobId INT NOT NULL,
PurchaseId INT NOT NULL,
EmployeeId INT NOT NULL,
AssignDate DATE NOT NULL,
PRIMARY KEY (JobId),
FOREIGN KEY (EmployeeId) REFERENCES Employee (EmployeeId)
);
--Insert data--
INSERT INTO Client VALUES
(1, 'Adidas', '123 Adidas Lane', 'Adida', '22209', '1-800-555-1987', 'corporate#adidas.com');
INSERT INTO Client VALUES
(2, 'Nike', '234 Nike Drive', 'Nikail', '22182', '1-888-555-9876', 'corporate#nike.com');
INSERT INTO Client VALUES
(3, 'Puma', '345 Puma Blvd', 'Puma City', '20912', '1-800-555-6247', 'corporate#puma.com');
INSERT INTO Client VALUES
(4, 'Reebok', '456 Reebok Cove', 'Old Reebok', '20902', '1-800-555-1000', 'corporate#reebok.com');
INSERT INTO Client VALUES
(5, 'Vans', '567 Vans Lane', 'Vancouver', '20725', '1-900-666-2000', 'corporate#vans.com');
INSERT INTO Client VALUES
(6, 'Jordan', '234 Nike Drive', 'Nikail', '22182', '1-888-555-8765', 'corporate#jordan.com');
INSERT INTO Client VALUES
(7, 'Diadora', '345 Puma Blvd', 'Puma City', '20912', '1-800-555-4126', 'corporate#diadora.com');
INSERT INTO SoccerBall VALUES
(11, 1, 'blue', 'felt');
INSERT INTO SoccerBall VALUES
(12, 3, 'red', 'leather');
INSERT INTO SoccerBall VALUES
(13, 3, 'yellow', 'faux leather');
INSERT INTO SoccerBall VALUES
(14, 5, 'black', 'leather');
INSERT INTO SoccerBall VALUES
(15, 4, 'white', 'faux leather');
INSERT INTO SoccerBall VALUES
(16, 3, 'purple', 'rubber');
INSERT INTO SoccerBall VALUES
(17, 1, 'blue', 'faux leather');
INSERT INTO Purchase VALUES
(21, 2, 11, DATE '2013-01-01');
INSERT INTO Purchase VALUES
(22, 4, 12, DATE '2012-03-24');
INSERT INTO Purchase VALUES
(23, 7, 15, DATE '2013-05-01');
INSERT INTO Purchase VALUES
(24, 5, 13, DATE '2005-12-30');
INSERT INTO Purchase VALUES
(25, 6, 16, DATE '1999-01-23');
INSERT INTO Employee VALUES
(111, 'Vivin Viswanathan');
INSERT INTO Employee VALUES
(222, 'Andy Edwards');
INSERT INTO Employee VALUES
(333, 'Frank Hellwig');
INSERT INTO Employee VALUES
(444, 'Vandana Janeja');
INSERT INTO Job VALUES
(1111, 21, 111, DATE '2013-01-02');
INSERT INTO Job VALUES
(5555, 22, 111, DATE '2012-03-26');
INSERT INTO Job VALUES
(2222, 23, 222, DATE '2013-05-08');
INSERT INTO Job VALUES
(3333, 24, 222, DATE '2006-01-02');
INSERT INTO Job VALUES
(4444, 25, 111, DATE '1999-01-30');
--Queries--
--Query 1--Show me the information in the database
SELECT * FROM Client;
SELECT * FROM SoccerBall;
SELECT * FROM Purchase;
SELECT * FROM Employee;
SELECT * FROM Job;
--"Forgot" Quantity Attribute. Adding that--
ALTER TABLE Purchase ADD Quantity NUMBER(5);
UPDATE Purchase SET Quantity = '12000' WHERE ClientId = '1';
UPDATE Purchase SET Quantity = '2492' WHERE ClientId = '2';
UPDATE Purchase SET Quantity = '94203' WHERE ClientId = '3';
UPDATE Purchase SET Quantity = '4394' WHERE ClientId = '4';
UPDATE Purchase SET Quantity = '0' WHERE ClientId = '5';
UPDATE Purchase SET Quantity = '4832' WHERE ClientId = '6';
UPDATE Purchase SET Quantity = '10002' WHERE ClientId = '7';
SELECT * FROM Purchase;
--Queries Continued--
--Query 2--I want to know how many clients we have
SELECT COUNT(*) FROM Client;
--Query 3--Which client ordered the most soccer balls?***********
SELECT MAX(Quantity), ClientName
FROM Purchase P, Client C
WHERE P.ClientId = C.ClientId;
--Query 4--How many projects does each employe have?***********
SELECT EmployeeId COUNT(*)
FROM Job
GROUP BY EmployeeId;
--Query 5--First purchases, first served. Show me the order of the purchases by date***********
SELECT ClientName, PurchaseDate
FROM Purchase P, Client C
WHERE P.ClientId = C.ClientId AND ORDER BY PurchaseDate;
--Query 6--Show me what kind of balls were purchased***********
SELECT B.BallId, B.BallSize, B.Color, B.Material
FROM SoccerBall B, Purchase P, Client C
WHERE P.ClientId = C.ClientId AND P.BallId = B.BallId AND C.ClientId = 1;
--Query 7--Show me who purchased what balls**************
SELECT B.BallId, B.BallSize, B.Color, B.Material, C.ClientId, ClientName
FROM SoccerBall B, Purchase P, Client C
WHERE P.ClientId = C.ClientId AND P.BallId = B.BallId GROUP BY ClientName;
Thanks so much!
You have several issues with your queries.
Query 3 is missing a GROUP BY with the aggregate function:
SELECT MAX(Quantity), ClientName
FROM Purchase P
INNER JOIN Client C
ON P.ClientId = C.ClientId
GROUP BY ClientName;
Query 4 is missing a comma between the columns employeeId and count(*):
SELECT EmployeeId, COUNT(*)
FROM Job
GROUP BY EmployeeId;
Query 5 has an errant AND before the ORDER BY:
SELECT ClientName, PurchaseDate
FROM Purchase P
INNER JOIN Client C
ON P.ClientId = C.ClientId
ORDER BY PurchaseDate;
Query 6 is you want all of the balls purchased, I don't think you want a filter on ClientId:
SELECT B.BallId, B.BallSize, B.Color, B.Material
FROM SoccerBall B
INNER JOIN Purchase P
ON P.BallId = B.BallId
INNER JOIN Client C
ON P.ClientId = C.ClientId;
Query 7 is using a GROUP BY on one column only which will not work correctly:
SELECT B.BallId, B.BallSize, B.Color, B.Material, C.ClientId, ClientName
FROM SoccerBall B
INNER JOIN Purchase P
ON P.BallId = B.BallId
INNER JOIN Client C
ON P.ClientId = C.ClientId;
See SQL Fiddle with Demo.
As a side note, you will notice that I updated the queries to use INNER JOIN syntax instead of commas between the tables and the joins in the WHERE clause.
This one works. Try it out.
' --Drop tables--
DROP TABLE job;
DROP TABLE employee;
DROP TABLE purchase;
DROP TABLE soccerball;
DROP TABLE client;
--Create tables--
CREATE TABLE client
(
clientid INT NOT NULL IDENTITY(1, 1),
clientname VARCHAR(20) NOT NULL,
street VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
zipcode VARCHAR(5) NOT NULL,
phone VARCHAR(15) NULL,
emailaddr VARCHAR(50) NULL,
PRIMARY KEY(clientid)
);
CREATE TABLE soccerball
(
ballid INT NOT NULL,
ballsize NUMERIC(1) NOT NULL,
color VARCHAR(20) NOT NULL,
material VARCHAR(20) NOT NULL,
PRIMARY KEY(ballid)
);
CREATE TABLE purchase
(
purchaseid INT NOT NULL,
clientid INT NOT NULL,
ballid INT NOT NULL,
purchasedate DATETIME NOT NULL,
PRIMARY KEY (purchaseid),
FOREIGN KEY (clientid) REFERENCES client (clientid),
FOREIGN KEY (ballid) REFERENCES soccerball (ballid)
);
CREATE TABLE employee
(
employeeid INT NOT NULL,
employeename VARCHAR(50) NOT NULL,
PRIMARY KEY (employeeid)
);
CREATE TABLE job
(
jobid INT NOT NULL,
purchaseid INT NOT NULL,
employeeid INT NOT NULL,
assigndate DATETIME NOT NULL,
PRIMARY KEY (jobid),
FOREIGN KEY (employeeid) REFERENCES employee (employeeid)
)
--Insert data--
INSERT INTO dbo.client
(clientname,
street,
city,
zipcode,
phone,
emailaddr)
VALUES ( 'Adidas',
'123 Adidas Lane',
'Adida',
'22209',
'1-800-555-1987',
'corporate#adidas.com')
INSERT INTO client
(clientname,
street,
city,
zipcode,
phone,
emailaddr)
VALUES ('Nike',
'234 Nike Drive',
'Nikail',
'22182',
'1-888-555-9876',
'corporate#nike.com')
INSERT INTO client
VALUES ( 'Puma',
'345 Puma Blvd',
'Puma City',
'20912',
'1-800-555-6247',
'corporate#puma.com')
INSERT INTO client
VALUES ( 'Reebok',
'456 Reebok Cove',
'Old Reebok',
'20902',
'1-800-555-1000',
'corporate#reebok.com')
INSERT INTO client
VALUES ( 'Vans',
'567 Vans Lane',
'Vancouver',
'20725',
'1-900-666-2000',
'corporate#vans.com')
INSERT INTO client
VALUES ( 'Jordan',
'234 Nike Drive',
'Nikail',
'22182',
'1-888-555-8765',
'corporate#jordan.com')
INSERT INTO client
VALUES ( 'Diadora',
'345 Puma Blvd',
'Puma City',
'20912',
'1-800-555-4126',
'corporate#diadora.com')
INSERT INTO soccerball
VALUES (11,
1,
'blue',
'felt');
INSERT INTO soccerball
VALUES (12,
3,
'red',
'leather');
INSERT INTO soccerball
VALUES (13,
3,
'yellow',
'faux leather');
INSERT INTO soccerball
VALUES (14,
5,
'black',
'leather');
INSERT INTO soccerball
VALUES (15,
4,
'white',
'faux leather');
INSERT INTO soccerball
VALUES (16,
3,
'purple',
'rubber');
INSERT INTO soccerball
VALUES (17,
1,
'blue',
'faux leather');
INSERT INTO purchase
VALUES (21,
2,
11,
'2013-01-01');
INSERT INTO purchase
VALUES (22,
4,
12,
'2012-03-24');
INSERT INTO purchase
VALUES (23,
7,
15,
'2013-05-01');
INSERT INTO purchase
VALUES (24,
5,
13,
'2005-12-30');
INSERT INTO purchase
VALUES (25,
6,
16,
'1999-01-23');
INSERT INTO employee
VALUES (111,
'Vivin Viswanathan');
INSERT INTO employee
VALUES (222,
'Andy Edwards');
INSERT INTO employee
VALUES (333,
'Frank Hellwig');
INSERT INTO employee
VALUES (444,
'Vandana Janeja');
INSERT INTO job
VALUES (1111,
21,
111,
'2013-01-02');
INSERT INTO job
VALUES (5555,
22,
111,
'2012-03-26');
INSERT INTO job
VALUES (2222,
23,
222,
'2013-05-08');
INSERT INTO job
VALUES (3333,
24,
222,
'2006-01-02');
INSERT INTO job
VALUES (4444,
25,
111,
'1999-01-30');
--Queries--
--Query 1--Show me the information in the database
SELECT *
FROM client;
SELECT *
FROM soccerball;
SELECT *
FROM purchase;
SELECT *
FROM employee;
SELECT *
FROM job;
--"Forgot" Quantity Attribute. Adding that--
ALTER TABLE purchase
ADD quantity NUMERIC;
UPDATE purchase
SET quantity = '12000'
WHERE clientid = '1';
UPDATE purchase
SET quantity = '2492'
WHERE clientid = '2';
UPDATE purchase
SET quantity = '94203'
WHERE clientid = '3';
UPDATE purchase
SET quantity = '4394'
WHERE clientid = '4';
UPDATE purchase
SET quantity = '0'
WHERE clientid = '5';
UPDATE purchase
SET quantity = '4832'
WHERE clientid = '6';
UPDATE purchase
SET quantity = '10002'
WHERE clientid = '7';
SELECT *
FROM purchase;
--Queries Continued--
--Query 2--I want to know how many clients we have
SELECT Count(*)
FROM client;
--Query 3--Which client ordered the most soccer balls?***********
SELECT Max(quantity),
clientname
FROM purchase P,
client C
WHERE P.clientid = C.clientid
GROUP BY clientname
--Query 4--How many projects does each employe have?***********
SELECT Count(*)
FROM job
--Query 5--First purchases, first served. Show me the order of the purchases by date***********
SELECT clientname,
purchasedate
FROM purchase P,
client C
WHERE P.clientid = C.clientid
ORDER BY purchasedate;
--Query 6--Show me what kind of balls were purchased***********
SELECT B.ballid,
B.ballsize,
B.color,
B.material
FROM soccerball B,
purchase P,
client C
WHERE P.clientid = C.clientid
AND P.ballid = B.ballid
AND C.clientid = 1;
--Query 7--Show me who purchased what balls**************
SELECT B.ballid,
B.ballsize,
B.color,
B.material,
C.clientid,
clientname
FROM soccerball B,
purchase P,
client C
WHERE P.clientid = C.clientid
AND P.ballid = B.ballid
GROUP BY B.ballid,
B.ballsize,
B.color,
B.material,
C.clientid,
clientname'

PostgreSQL - Calculation count the elements in the hierarchy

There is a table:
CREATE TABLE product_categories (
id INT NOT NULL PRIMARY KEY,
parent INT NOT NULL,
name varchar(50) NOT NULL,
isProduct boolean NOT NULL
);
Is there any way to calculate count products in the each category?
That is:
INSERT INTO product_categories VALUES (1, NULL, 'Main', 'no');
INSERT INTO product_categories VALUES (2, 1, 'Plant', 'no');
INSERT INTO product_categories VALUES (3, 2, 'Cactus', 'yes');
INSERT INTO product_categories VALUES (4, 2, 'Spruce', 'yes');
INSERT INTO product_categories VALUES (5, 2, 'Birch', 'yes');
INSERT INTO product_categories VALUES (6, 2, 'Pine', 'yes');
INSERT INTO product_categories VALUES (7, 1, 'Stock', 'no');
INSERT INTO product_categories VALUES (8, 7, 'Spade', 'yes');
INSERT INTO product_categories VALUES (9, 7, 'Watering can', 'yes');
and should to receive:
Category | Count
Main | 6
Plant | 4
Stock | 2
You need to use a Recursive Common Table Expression
WITH RECURSIVE Parents AS
( SELECT ID, Parent, Name, IsProduct
FROM product_categories
WHERE Parent IS NOT NULL
UNION ALL
SELECT c.ID, p.Parent, c.Name, c.IsProduct
FROM product_categories c
INNER JOIN Parents p
ON p.ID = c.Parent
)
SELECT pc.Name,
COUNT(*) AS Products,
ARRAY_AGG(p.Name) AS ProductList
FROM product_categories pc
INNER JOIN Parents p
ON p.Parent = pc.ID
WHERE p.IsProduct = 'yes'
GROUP BY pc.Name
Working Example