sql—query power from the db2 textbook. expressive power topics 5.1 case expressions 5.2...

12
SQL—Query Power From the DB2 textbook

Upload: jesse-mills

Post on 13-Dec-2015

215 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

SQL—Query Power

From the DB2 textbook

Page 2: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

Expressive Power Topics5.1 Case Expressions 5.2 Subqueries—Table expressions5.3 Table Functions (later)5.4 Explicit Joins—left, right, full outer joins5.5 Extended FROM Clause5.6 Super-groups OLAPs (later)5.7 Common Table Expression--WITH5.8 Recursion

Page 3: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

***** CASE Expressions *****;CREATE TABLE officers (name Varchar(20), status Integer, rank Varchar(20), title Varchar(20));

INSERT INTO officers VALUES ('Miner', 1, 'Major', NULL), ('Bligh', 2, 'Captain', NULL), ('Strangelove', 3, NULL, 'Doctor'), ('Kirk', 8, 'Captain', NULL);

SELECT name, CASE status WHEN 1 THEN 'Active Duty' WHEN 2 THEN 'Reserve' WHEN 3 THEN 'Special Assignment' WHEN 4 THEN 'Retired' ELSE 'Unknown' END AS statusFROM officers;

E TABLE vehicles (LICENSE integer, RENEWAL_DATE date, TYPE varchar(10), WEIGHT decimal(7,2), NWHEELS smallint);

INSERT INTO vehicles VALUES (111, '10-03-1994', 'Truck', 7500, 6),

(555, '01-06-1997', 'Car', 5500, 4), (7292, '02-02-1993', 'Car', 6000, 5), (55775, '07-24-1995', 'Motorcycle', 2200, 2), (3364, '08-25-1995', 'Bike', 50, 2); SELECT license, CASE type WHEN 'Car' THEN 0.05 * weight WHEN 'Truck' THEN 25.00 * nwheels WHEN 'Motorcycle' THEN 35.00 ELSE NULL END AS feeFROM vehiclesWHERE year(renewal_date) < 1995;

Page 4: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

More on CASECREATE TABLE machines (SERIALNO integer, TYPE varchar(15), YEAR smallint, HOURS_USED float, ACCIDENTS smallint);

INSERT INTO machines VALUES (101, 'sand blaster', 1997, 5000, 10),

(102, 'sand blaster', 1997, 15000, 5), (201, 'chain saw', 1997, 1000, 5), (202, 'chain saw', 1997, 500, 0), (301, 'flame thrower', 1997, 0, 0);

SELECT type, CASE WHEN sum(hours_used) > 0 THEN

sum(accidents)/sum(hours_used) ELSE NULL END AS accident_rateFROM machinesGROUP BY type;

UPDATE propertiesSET taxrate = CASE city WHEN 'San Jose' THEN taxrate WHEN 'Santa Clara' THEN taxrate + .005 WHEN 'Campbell' THEN taxrate + .005 WHEN 'Los Gatos' THEN taxrate + .008 ELSE raise_error('70007', 'Parcel ' || parcelno || ' has unknown city') END;

SELECT * FROM properties;

SELECT name, coalesce(rank, title) AS rank_or_titleFROM officersWHERE status IN (1, 2, 3);

SELECT name, CASE WHEN rank IS NOT NULL THEN rank ELSE title END AS rank_or_titleFROM officersWHERE status IN (1, 2, 3);

Page 5: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

Table ExpressionCREATE TABLE EMP (NAME char(15), DEPTNO char(3), JOB varchar(20), MANAGER char(10), RATING smallint, SALARY decimal(8,2), BONUS decimal(8,2), STARTDATE date);

SELECT maxrating, count(*) AS n_deptsFROM (SELECT deptno, min(rating), max(rating) FROM emp GROUP BY deptno) AS ratingstats(deptno, minrating, maxrating)GROUP BY maxrating;

Page 6: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

Table Functions:Externally defined table-valued functions

CREATE FUNCTION sales (Varchar(15)) RETURNS TABLE (saledate Date,

product Varchar(15), quantity Integer, price Integer)EXTERNAL NAME 'salesfun!sales' ….

SELECT avg(price) AS avgpriceFROM TABLE(sales('Boulder'))

WHERE product = 'Stapler'AND year(saledate) = 1997;

SELECT month(saledate) AS month, sum(quantity * price) AS revenueFROM TABLE(sales('Denver')) AS SWHERE year(S.saledate) = 1997GROUP BY month(S.saledate);

Page 7: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

Joining with a Table functionCREATE TABLE SALESPLAN (year Integer, store Varchar(15), product Varchar(15), monthly_units Integer);

SELECT month(sales.saledate) AS month, plan.store, plan.product, plan.monthly_units AS units_planned, sum(sales.quantity) AS units_soldFROM salesplan AS plan, TABLE(sales(plan.store)) AS salesWHERE plan.year = 1997AND plan.product = sales.productAND plan.year = year(sales.saledate)GROUP BY month(sales.saledate), plan.store, plan.product, plan.monthly_unitsHAVING sum(sales.quantity) >= 1.5 * plan.monthly_units;

Page 8: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

CREATE TABLE fedemp (NAME varchar(15), SALARY decimal(8,2), MANAGER varchar(15));

Find the employees who have Hooever as a manager (at any level in the management chain) and make more than 100K.

WITH agents(name, salary) AS ((SELECT name, salary FROM fedemp WHERE manager = 'Hoover') UNION ALL (SELECT f.name, f.salary FROM agents AS a, fedemp AS f WHERE f.manager = a.name))SELECT name FROM agentsWHERE salary > 100000;

Recursion –page 253

Page 9: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

Page 262: flights from San Francisco to New York,in less than 3 segments (also you can exclude flight that ends in San Francisco or start in New York).

create table flights (flightno varchar(5), origin char(3), destination char(3), cost integer);

insert into flights values ('HY120', 'DFW', 'JFK', 225), ('HY130', 'DFW', 'LAX', 200), ('HY140', 'DFW', 'ORD', 100), ('HY150', 'DFW', 'SFO', 300), ('HY210', 'JFK', 'DFW', 225), ('HY240', 'JFK', 'ORD', 250), ('HY310', 'LAX', 'DFW', 200), ('HY350', 'LAX', 'SFO', 50), ('HY410', 'ORD', 'DFW', 100), ('HY420', 'ORD', 'JFK', 250), ('HY450', 'ORD', 'SFO', 275), ('HY510', 'SFO', 'DFW', 300), ('HY530', 'SFO', 'LAX', 50), ('HY540', 'SFO', 'ORD', 275);

WITH trips(destination, route, nsegs, totalcost) AS ((SELECT destination, CAST(destination AS Varchar(20)), 1, cost FROM flights WHERE origin = 'SFO') UNION ALL (SELECT f.destination, CAST(t.route || ', ' || f.destination AS Varchar(20)), t.nsegs + 1, t.totalcost + f.cost FROM trips t, flights f WHERE t.destination = f.origin AND f.destination <> 'SFO' AND f.origin <> 'JFK' AND t.nsegs < 3 )) SELECT route, totalcost FROM tripsWHERE destination = 'JFK'AND totalcost = (SELECT min(totalcost) FROM trips WHERE destination = 'JFK');

Page 10: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

Back to Datalog:People working for Hoover making >100K

fed('Elliot Ness', 150000, 'Hoover').fed('Ryan Baker', 75000, 'Hoover').fed('Bill Bathgate', 140000, 'Elliot Ness').fed('Susan Crandall', 50000, 'Bill Bathgate').fed ('Sam Anders', 125000, 'Steve Smith').

agents(E, Sal) <- fed(E, Sal, 'Hoover').agents(E2, Sal2) <- agents(E1, Sal1), fed(E2, Sal2, E1).

hpaid(Name) <- agents(Name, Sal), Sal>100000.

export hpaid(N).

Page 11: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

Back to Datalog% Find flight from San Francisco: DB2 at page 262% instead of using SQL concatenation we will use lists% To avoid cycles, we check that we have not more than 3 legs and % and avoid SFO(NY) as end or start of leg.

database({flights(flightno: string, origin: string destination: string, cost: integer)}). trips(Dest, [], 1, Cost) <- flights(_,'SFO', Dest, Cost).

trips(Dest2, [Dest1|L], Nsegs2, Cost2) <- trips(Dest1, L, Nsegs1, Cost1), Dest1~='JFK', Nsegs1 < 3, flights(_, Dest1, Dest2, To, C), Dest2~='SFO', Cost2=Cost1+C, Nsegs2=Nsegs1+1.

export trips (D, L , Nsegs, Cost).export trips ($D, L , Nsegs, Cost).

Page 12: SQL—Query Power From the DB2 textbook. Expressive Power Topics 5.1 Case Expressions 5.2 Subqueries—Table expressions 5.3 Table Functions (later) 5.4 Explicit

A More General Solutiontrips(Dest, ['SFO'], Cost) <-

flights(_,'SFO', Dest, Cost).trips(Dest2, [Dest1|L], Cost2) <-

trips(Dest1, L, Cost1), flights(_, Dest1, Dest2, To, C),

Dest1~='JFK', ~member(Dest2, L), Cost2=Cost1+C.export trips (D, L , Cost).export trips ($D, L , Cost).

member(X, [X|_]).member(X, [_|L2]) <- member(X, L2).% We might still want to use a count to avoid

too many segments% Dest1~='JFK' will stop when we get to NY

Printing… ‘NY’ firstexport ny_first(X).Ny_firstl(X) <- trips ('NY', L ),

member(X, L).

Printing… ‘SF’ first—we reverse the list

export sf_first(X).rev([ ], L) <- trips ('NY', L ).rev([X|R], L) <- rev(R, [X|L]).sf_first(X) <- rev(R, [ ]),

member(X, R).