Postgres Sql || Practicing Group By and Order By



Postgres Sql || Practicing Group By and Order By

Postgres Sql || Practicing Group By and Order By

PostGres Query:-
———————————————————————————————
— Create the database if not exists
CREATE DATABASE IF NOT EXISTS “awesome_chocolates”;
c “awesome_chocolates”;

drop table Geo;
drop table “Customer”;
drop table “Sales”;
— Create the Geo table
CREATE TABLE Geo (
GeoID varchar(4) PRIMARY KEY,
Geo text,
Region text
);

— Create the Customer table
CREATE TABLE Customer (
CustomerID serial PRIMARY KEY,
FirstName text,
LastName text,
Email text
);

— Create the Sales table
CREATE TABLE Sales (
SaleID serial PRIMARY KEY,
CustomerID integer,
Product text,
Amount numeric,
SaleDate date,
FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID)
);

— Insert 100 rows into Geo table
DO $$
BEGIN
FOR i IN 1..100 LOOP
INSERT INTO Geo (GeoID, Geo, Region) VALUES (i::text, ‘Geo’ || i, ‘Region’ || (i % 5 + 1));
END LOOP;
END $$;

— Insert 100 rows into Customer table
DO $$
BEGIN
FOR i IN 1..100 LOOP
INSERT INTO Customer (FirstName, LastName, Email) VALUES (‘First’ || i, ‘Last’ || i, ’email’ || i || ‘@example.com’);
END LOOP;
END $$;

— Insert 100 rows into Sales table
DO $$
DECLARE
customer_id integer;
BEGIN
FOR i IN 1..100 LOOP
INSERT INTO Sales (CustomerID, Product, Amount, SaleDate)
VALUES (i, ‘Product’ || (i % 10 + 1), (i * 10)::numeric, CURRENT_DATE – (i % 30));
END LOOP;
END $$;

select * from Customer;
select * from Geo;
select * from Sales;

select product,sum(Amount) from Sales group by product order by sum(Amount);

select saledate, count(product) from sales group by saledate;

select region,count(geo) from Geo group by Region order by Region;

—————————————————————————————————————

Library:- https://srtechacademy.spayee.com/s/pages/blogs

I Hope You Were Able To Understand All The Concepts I Tried To Explain.
Hope You Like The Video…