0% found this document useful (0 votes)
9 views33 pages

Lecture Grpby & Comples Joins.

The document discusses SQL functions like group by, subqueries, joins, aggregate functions, and how to get summary results from a database. It provides examples of calculating averages, counts, minimums and maximums from tables as well as grouping and filtering results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views33 pages

Lecture Grpby & Comples Joins.

The document discusses SQL functions like group by, subqueries, joins, aggregate functions, and how to get summary results from a database. It provides examples of calculating averages, counts, minimums and maximums from tables as well as grouping and filtering results.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Group by, sub-queries and

complex joins

1
The SHR table
shr
shrcode shrfirm shrprice shrqty shrdiv shrpe

FC Freedonia Copper 27.50 10529 1.84 16


PT Patagonian Tea 55.25 12635 2.50 10
AR Abyssinian Ruby 31.82 22010 1.32 13
SLG Sri Lankan Gold 50.37 32868 2.68 16
ILZ Indian Lead & Zinc 37.75 6390 3.00 12
BE Burmese Elephant 0.07 154713 0.01 3
BS Bolivian Sheep 12.75 231678 1.78 11
NG Nigerian Geese 35.00 12323 1.68 10
CS Canadian Sugar 52.78 4716 2.50 15
ROF Royal Ostrich Farms 33.75 1234923 3.00 6

2
Calculating
SELECT shrfirm, shrprice, shrqty,
shrdiv/shrprice*100 as YIELD
FROM shr;
shrfirm shrprice shrqty yield
Freedonia Copper 27.50 10,529 6.69
Patagonian Tea 55.25 12,635 4.52
Abyssinian Ruby 31.82 22,010 4.15
Sri Lankan Gold 50.37 32,868 5.32
Indian Lead & Zinc 37.75 6,390 7.95
Burmese Elephant 0.07 154,713 14.29
Bolivian Sheep 12.75 231,678 13.96
Nigerian Geese 35.00 12,323 4.80
Canadian Sugar 52.78 4,716 4.74
3
Royal Ostrich Farms 33.75 1,234,923 8.89
“Aggregate” functions
• COUNT, AVG, SUM, MIN, and MAX
Find the average dividend.
SELECT AVG(shrdiv) AS avgdiv FROM shr;
avgdiv
2.03

What is the average yield for the portfolio?


SELECT AVG(shrdiv/shrprice*100) AS
avgyield
For definitions of the aggregate functions, see …
FROM shr;
avgyield
http://www.postgresql.org/docs/8.4/static/functions-aggregate.html
7.53 4
has
has

5
6
Select count(Country) from Menu;

How many different countries of origin are recorded in the Menu


table.

This …
count( <some column name>)
… only counts the non null values in that column.

7
Min and Max functions:
Give the cheapest Italian Pizza;

Select min(price) from menu where country = ‘ITALY’;

Give price of the most expensive pizza.

Select max(price) from menu;

8
9
Group by and having.

Select country, avg(price) from menu where


Country is not null group by country;

Give the average price of pizzas for each country of


Origin, do not list countries with only one pizza.

Select country, avg(price) from menu where county is


Not null group by country having count(*) >1;

10
nation
NATION and STOCK
natcode natname exchrate
UK United Kingdom 1.00
USA United States 0.67
AUS Australia 0.46
IND India 0.0228

stock

stkcode stkfirm stkprice stkqty stkdiv stkpe natcode


FC Freedonia Copper 27.50 10529 1.84 16 UK
PT Patagonian Tea 55.25 12635 2.50 10 UK
AR Abyssinian Ruby 31.82 22010 1.32 13 UK
SLG Sri Lankan Gold 50.37 32868 2.68 16 UK
ILZ Indian Lead &Zinc 37.75 6390 3.00 12 UK
BE Burmese Elephant .07 154713 0.01 3 UK
BS Bolivian Sheep 12.75 231678 1.78 11 UK
NG Nigerian Geese 35.00 12323 1.68 10 UK
CS Canadian Sugar 52.78 4716 2.50 15 UK
ROF Royal Ostrich Farms 33.75 1234923 3.00 6 UK
MG Minnesota Gold 53.87 816122 1.00 25 USA
GP Georgia Peach 2.35 387333 .20 5 USA
NE Narembeen Emu 12.34 45619 1.00 8 AUS
QD Queensland Diamond 6.73 89251 .50 7 AUS
IR Indooroopilly Ruby 15.92 56147 .50 20 AUS
BD Bombay Duck 25.55 167382 1.00 12 IND 11
Report by nation the total value of stockholdings.
GROUP BY
SELECT natname, SUM(stkprice*stkqty*exchrate)
AS stkvalue
FROM stock, nation
WHERE stock.natcode = nation.natcode
GROUP BY natname;

natname stkvalue

Australia 946430.65
India 97506.71
United Kingdom 48908364.25
United States 30066065.54 12
HAVING – like WHERE, but
after the grouping
Report the total value of stocks for nations with two or more listed stocks. (The
“two or more listed stocks” refers to a property of the groupings, so that part is
performed after the grouping.)

SELECT natname, SUM(stkprice*stkqty*exchrate) AS


stkvalue
FROM stock, nation
natname stkvalue
WHERE stock.natcode = nation.natcode
Australia 946430.65
GROUP BY natname United Kingdom 48908364.25

HAVING COUNT(*) >= 2; United States 30066065.54

13
Discussion about optional lab
exercises.

This is a blank slide.

14
Subqueries
• A query within a query
Report all firms with a PE ratio greater than the average for the
portfolio.

SELECT shrfirm, shrpe FROM shr WHERE


shrpe > (
avg
SELECT AVG(shrpe)FROM shr 11.2
shrfirm ); shrpe (1 row)
Freedonia Copper 16
Abyssinian Ruby 13
Sri Lankan Gold 16
Indian Lead & Zinc 12
Canadian Sugar 15
15
Type I Nested Queries
(Subqueries)
• Query inside a query
• Use in WHERE and HAVING conditions
• Executes one time

16
Using subqueries to find the maximum
(or minimum)
Give pizza and prices for pizzas that are more expensive than
all Italian pizzas.

SELECT pizza, price


FROM menu
WHERE price >= (
SELECT max(price)
FROM menu price
WHERE country = ‘italy’
7.8
);

17
Alternate way to find the maximum (or
minimum): “ALL”
Give pizza and prices for pizzas that are
more expensive than all Italian pizzas.

SELECT pizza, price


FROM menu
price
WHERE price >= ALL (
SELECT price
6.2
FROM menu 7.4
WHERE country = ‘italy’
); 7.8
7.4
Raymond prefers to use the equivalent approach
which was on the previous slide, but you need 7.4
to be able to read a query containing “ALL”.
18
Another ALL example
SELECT pizza , price
FROM menu

WHERE price <= ALL


(SELECT price from menu);

… but that’s equivalent to …

WHERE price =
(SELECT min(price) from menu); 19
ANY operator
List pizzas with at least one ‘meat’ ingredient.

SELECT DISTINCT pizza


FROM recipe
ingredient
WHERE ingredient = ANY ( ham
SELECT ingredient bacon
FROM items
cabanossi
WHERE type = ‘meat’
); salami
… but Raymond prefers to use the pepperoni
equivalent approach on the next (5 rows)
20

slide, using “IN” ...


In: an Alternate to ANY
List pizzas with at least one ‘meat’ ingredient.

SELECT DISTINCT pizza ingredient


FROM recipe ham
WHERE ingredient IN ( bacon
SELECT ingredient cabanossi
FROM items salami
WHERE type = ‘meat’); pepperoni
(5 rows)
21
Rules for using ALL and ANY
in returns
• When a subquery subqueries
more than one value, ANY
and ALL will be used to link the subquery and main
query
• When ALL is used, every value returned by the
subquery must satisfy the comparison operation
• Whe ANY is used, one or more values returned by
the subquery must satisfy the comparison operation
• “IN” is equivalent to “= ANY”
• “NOT IN” is equivalent to “<> ALL”

22
Type II Nested Queries
(Correlated Subqueries)
• Not in this subject
• At least not for P and C;
• Maybe D and HD
• Reference to outer query
• Executes one time for each row of outer query

23
Revision: the Natural Join
• Join creates a new table from two existing tables by
matching on a column common to both tables
• Eg.SELECT *
FROM stock NATURAL JOIN nation;
• Cross product form …
• The new table contains two identical columns
SELECT * FROM stock, nation
WHERE stock.natcode = nation.natcode;

24
Left Outer join
• Not in this subject
• At least not for P and C; maybe D and HD
• A natural join plus those rows from t1 not included in
the natural join
• SELECT *
FROM t1 LEFT JOIN t2 USING (id);
t1 t2

id col1 id col2 t1.id col1 t2.id col2


1 a 1 x 1 a 1 x
2 b 3 y 2 b null null
25
3 c 5 z 3 c 3 y
Right Outer join

• Not in this subject


• At least not for P and C; maybe D and HD
• A natural join plus those rows from t2 not included
in the natural join
• SELECT *
t1 t2 JOIN t2 USING (id);
FROM t1 RIGHT
id col1 id col2 t1.id col1 t2.id col2
1 a 1 x 1 a 1 x
2 b 3 y 3 c 3 y
26
3 c 5 z null null 5 z
Theta join
• A join that may include comparison operators other than
just “=“, such as …
• <> > >= < <=
• A theta join is the most general form of join.
• Examples of using things other than “=“ follow …

27
Self-Join
• Join a table to itself
• Usually involve a self-referencing relationship supervises
• Useful to find relationships
among rows of the same emp
table

28
Joining a table with itself
emp
empno empfname empsalary deptname bossno
1 Alice 75000 Management
2 Ned 45000 Marketing 1
3 Andrew 25000 Marketing 2
4 Clare 22000 Marketing 2
5 Todd 38000 Accounting 1
6 Nancy 22000 Accounting 5
7 Brier 43000 Purchasing 1
8 Sarah 56000 Purchasing 7 supervises
9 Sophie 35000 Personnel & PR 1

emp
emp
empno empfname empsalary deptname bossno
1 Alice 75000 Management
2 Ned 45000 Marketing 1
3 Andrew 25000 Marketing 2
4 Clare 22000 Marketing 2
5 Todd 38000 Accounting 1
6 Nancy 22000 Accounting 5
7 Brier 43000 Purchasing 1
8 Sarah 56000 Purchasing 7 29
9 Sophie 35000 Personnel & PR 1
Querying a recursive
relationship
Find the names of employees who earn more than their boss.

supervises
SELECT wrk.empfname
FROM emp wrk, emp boss
WHERE wrk.bossno = boss.empno emp
AND wrk.empsalary > boss.empsalary;

wrk boss
empno empfname empsalary deptname bossno empno empfname empsalary deptname bossno
2 Ned 45,000 Marketing 1 1 Alice 75,000 Management
3 Andrew 25,000 Marketing 2 2 Ned 45,000 Marketing 1
4 Clare 22,000 Marketing 2 2 Ned 45,000 Marketing 1
5 Todd 38,000 Accounting 1 1 Alice 75,000 Management
6 Nancy 22,000 Accounting 5 5 Todd 38,000 Accounting 1
7 Brier 43,000 Purchasing 1 1 Alice 75,000 Management
8 Sarah 56,000 Purchasing 7 7 Brier 43,000 Purchasing 1
9 Sophie 35,000 Personnel & PR 1 1 Alice 75,000 Management

30
empfname
Sarah
web links on aggregate functions

Also, but these can quickly get technical ...


http://www.postgresql.org/docs/8.4/static/functions-aggregate.html
http://www.postgresql.org/docs/8.4/static/tutorial-agg.html 31
web links on subqueries

Also, but these can quickly get technical ...


http://www.postgresql.org/docs/8.4/static/functions-subquery.html
32
web links on joins

Also, but these can quickly get technical ...


http://www.postgresql.org/docs/8.4/static/tutorial-join.html
http://www.postgresql.org/docs/8.4/static/queries-table-expressions.html#QUERIES-JOIN
33

You might also like