Jerry Post Copyright © 2013 DATABASE Database Management Systems Chapter 5 Advanced Queries 1.

Slides:



Advertisements
Similar presentations
ISOM3230 Business Applications Programming
Advertisements

© Paradigm Publishing, Inc Excel 2013 Level 2 Unit 1Advanced Formatting, Formulas, and Data Management Chapter 2Advanced Functions and Formulas.
Jerry Post Copyright © Database Management Systems Chapter 5 Advanced Queries.
PL/SQL.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
1 Materi Pendukung Pertemuan > Transaksi pendukung pada SQL Matakuliah: >/ > Tahun: > Versi: >
Proyek Queri-queri Lanjut dan Sub-subqueri. Variables dan Data.
1 Copyright © 2010 Jerry Post with additions & narration by M. E. Kabay. All rights reserved. Advanced Queries IS240 – DBMS Lecture # 8 – M.
Objectives In this chapter, you will learn about:
Introduction to Structured Query Language (SQL)
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
5 Chapter 5 Structured Query Language (SQL2) Revision.
Introduction to Structured Query Language (SQL)
Repeating Program Instructions Chapter Microsoft Visual Basic.NET: Reloaded 1.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Copyright © 2001 by Wiley. All rights reserved. Chapter 3: Variables, Assignment Statements, and Arithmetic Variables Assignment Statements Arithmetic.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Access Level Three [Functions] & “ And “ & [Expressions]
ASP.NET Programming with C# and SQL Server First Edition
Chapter 3 Query Language Database Application SAK 3408.
Copyright © 2010 Pearson Education, Inc. Publishing as Prentice Hall1 Exploring Microsoft Office Access Committed to Shaping the Next Generation.
IE 212: Computational Methods for Industrial Engineering
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
Chapter 4 Querying Based on G. Post, DBMS: Designing & Building Business Applications University of Manitoba Asper School of Business 3500 DBMS Bob Travica.
Jerry Post Copyright © Database Management Systems Chapter 5 Advanced Queries.
Banner and the SQL Select Statement: Part Four (Multiple Connected Select Statements) Mark Holliday Department of Mathematics and Computer Science Western.
Chapter 5 Advanced Querying
Analyzing Data For Effective Decision Making Chapter 3.
1 All Powder Board and Ski Oracle 9i Workbook Chapter 7: Integrity and Transactions Jerry Post Copyright © 2003.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
SQL (DDL & DML Commands)
Chapter Six: Working With Arrays in Visual Basic.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Jerry Post Copyright © Database Management Systems Chapter 5 Advanced Queries.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
1 All Powder Board and Ski Oracle 9i Workbook Chapter 4: Queries Jerry Post Copyright © 2003.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
1 Chapter 10 Joins and Subqueries. 2 Joins & Subqueries Joins – Methods to combine data from multiple tables – Optimizer information can be limited based.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
1 Chapter 3: Customize, Analyze, and Summarize Query Data Exploring Microsoft Office Access 2007.
1 Copyright © 2010 Jerry Post & M. E. Kabay. All rights reserved. Queries: Part 2 of 2 IS240 – DBMS Lecture # 7 – M. E. Kabay, PhD, CISSP-ISSMP.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
6-1 Chapter 6 Working with Arrays in VB.NET. 6-2 Learning Objectives Understand the use of list and table arrays in VB.NET projects and the difference.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
XP 1 Microsoft Office Excel 2003 Working With Formulas and Functions.
School of Computer & Communication of LNPU 辽宁石油化工大学计算机与通信工程学院 刘旸 1 数据库管理系统 Database Management Systems Chapter5 Advanced Queries 第五章 高级查询和子查询.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
1 All Powder Board and Ski SQL Server Workbook Chapter 5: Advanced Queries Jerry Post Copyright © 2003.
Retrieving Data Using the SQL SELECT Statement
Relational Database Design
Writing Basic SQL SELECT Statements
M. E. Kabay, PhD, CISSP-ISSMP V:
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
Microsoft Access Illustrated
Variables and Arithmetic Operations
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Database Systems: Design, Implementation, and Management Tenth Edition
Introduction to Computer Programming IT-104
Presentation transcript:

Jerry Post Copyright © 2013 DATABASE Database Management Systems Chapter 5 Advanced Queries 1

2 Objectives  How can SQL be used to answer more complex questions?  Why are some business questions more difficult than others?  How do you find something that did not happen?  How is a subquery used for IN and NOT IN conditions?  What are the common uses for subqueries?  What are correlated subqueries?  What tricky problems arise and how do you handle them in SQL?  What are the SQL data definition commands?  What SQL commands alter the data stored in tables?  How do you know if your query is correct?

Tables 3

Organization  Harder Questions  Not In, LEFT JOIN  Subqueries  UNION, Multiple JOIN columns, Recursive JOIN  Other SQL Commands  DDL: Data Definition Language  DML: Data Manipulation Language  OLAP  Microsoft SQL Server  Oracle  Microsoft Access Crosstab 4

Harder Questions  Which items have not been sold?  Which items were not sold in July 2013?  Which cat merchandise sold for more than the average sale price of cat merchandise?  Compute the merchandise sales by category in terms of percentage of total sales.  List all of the customers who bought something in March and who bought something in May. (Two tests on the same data!).  List dog merchandise with a list price greater than the sale price of the cheapest cat product.  Has one salesperson made all of the sales on a particular day?  Use Not Exists to list customers who have not bought anything.  Which merchandise has a list price greater than the average sale price of merchandise within that category?  List all the managers and their direct reports.  Convert age ranges into categories.  Classify payments by number of days late.  Which employees sold merchandise from every category?  List customers who adopted dogs and also bought cat products. 5

LEFT JOIN Problem 6 Which merchandise items have not been sold? ItemIDDescription 1Dog Kennel-Small 2Dog Kennel-Medium 3Dog Kennel-Large 4Dog Kennel-Extra Large 5Cat Bed-Small 6Cat Bed-Medium 7Dog Toy 8Cat Toy 9Dog Food-Dry-10 pound 10Dog Food-Dry-25 pound 11Dog Food-Dry-50 pound 12Cat Food-Dry-5 pound 13Cat Food-Dry-10 pound 14Cat Food-Dry-25 pound 15Dog Food-Can-Regular SaleIDItemID SaleItemMerchandise INNER JOIN is a filter that returns ONLY rows that exist in both tables. But SaleItem includes ONLY merchandise that HAS been sold.

LEFT JOIN Answer 7 Which merchandise items have not been sold? SELECT Merchandise.ItemID, Merchandise.Description, SaleItem.SaleID FROM Merchandise LEFT JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID WHERE SaleItem.SaleID Is Null; LEFT JOIN includes ALL rows from the table on the SQL left side and matching rows from the right-side table. RIGHT JOIN is similar. ItemIDDescription 1Dog Kennel-Small 10Dog Food-Dry-25 pound 11Dog Food-Dry-50 pound 12Cat Food-Dry-5 pound 13Cat Food-Dry-10 pound 14Cat Food-Dry-25 pound 15Dog Food-Can-Regular SaleIDItemID SaleItem Merchandise Query05_Fig03

LEFT JOIN Query 8 Note: LEFT/RIGHT depends on the SQL statement (Merchandise LEFT JOIN SaleItem). It is NOT set by the order of the tables in the display.

LEFT JOIN Result 9 Query1 ItemIDDescriptionSaleID 12Cat Food-Dry-5 pound 13Cat Food-Dry-10 pound

LEFT JOIN: Old Syntax 10 SELECT *(SQL Server) FROM Merchandise, SaleItem WHERE Merchandise.ItemID *= SaleItemID.ItemID And SaleItem.SaleID Is Null SELECT *(Oracle) FROM Merchandise, SaleItem WHERE Merchandise.ItemID = SaleItemID.ItemID (+) And SaleItem.SaleID Is Null Note that Oracle’s plus sign is on the opposite side from what you would expect. You should not use this syntax for new queries. It is hard to read. But you will likely encounter older queries in your work that use this syntax, so you need to recognize it and understand it is a LEFT join.

IN Function 11 SELECT * FROM Customer WHERE FirstName=N’Tim’ Or FirstName=N’David’ Or FirstName=N’Dale’; SELECT * FROM Customer WHERE FirstName IN (N’Tim’, N’David’, N’Dale’); The IN function compares a column to a set of values. IN is easier to write. Items are joined with an “Or” condition. Query05_Fig06a Query05_Fig06b

Query Sets (IN) 12 SELECT * FROM Merchandise WHERE ItemID IN (1,2,3,4,5,6,7,8,9,10,11,14,15); Query05_Fig07a FieldItemIDDescriptionQuantityOnHand TableCustomer SaleItem SortAscending CriteriaIn (1,2,3,4,5,…) Or ItemID Description QuantityOnHand ListPrice Merchandise List all merchandise with the ItemIDs of (1,2,3,4,5,6,7,8,9,10,11,14,15).

IN Condition as a JOIN 13 SELECT * FROM Merchandise WHERE ItemID IN (SELECT ItemID FROM SaleItem); Match ItemID values in the Merchandise table to those that were sold or listed in the SaleItem table. Query05_Fig07b

NOT IN: Things that did not happen 14 Which merchandise items have not been sold? Query05_Fig08 SELECT * FROM Merchandise WHERE ItemID NOT IN (SELECT ItemID FROM SaleItem); ItemIDDescription 1Dog Kennel-Small 2Dog Kennel-Medium 3Dog Kennel-Large 4Dog Kennel-Extra Large 5Cat Bed-Small 6Cat Bed-Medium 7Dog Toy 8Cat Toy 9Dog Food-Dry-10 pound 10Dog Food-Dry-25 pound 11Dog Food-Dry-50 pound 12Cat Food-Dry-5 pound 13Cat Food-Dry-10 pound 14Cat Food-Dry-25 pound 15Dog Food-Can-Regular Merchandise Think of taking the main list (Merchandise) and subtracting the items from the second list (SaleItem). Then display the ones that are left.

Not Sold Conditions (Date Subquery) 15 Which items were not sold in July 2013? Query05_Fig09 SELECT * FROM Merchandise WHERE ItemID NOT IN (SELECT ItemID FROM SaleItem INNER JOIN Sale ON Sale.SaleID=SaleItem.SaleID WHERE SaleDate BETWEEN ’01-JUL-2013’ AND ’31-JUL-2013’ );

Not Sold Conditions (Date LEFT JOIN--bad) 16 Which items were not sold in July 2013? Query05_Fig10 SELECT Merchandise.* FROM Sale INNER JOIN (Merchandise LEFT JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID) ON Sale.SaleID = SaleItem.SaleID WHERE SaleDate BETWEEN ’01-JUL-2013’ AND ’31-JUL-2013’; Probably will not run and might not return desired results. To work, the query must filter the SaleItem rows FIRST, Then apply the LEFT JOIN.

Not Sold Conditions (Date LEFT JOIN--good) 17 Which items were not sold in July 2013? JulyItems and Query05_Fig11 CREATE VIEW JulyItems AS SELECT Sale.SaleID, ItemID FROM Sale INNER JOIN SaleItem ON Sale.SaleID=SaleItem.SaleID WHERE SaleDate BETWEEN ’01-JUL-2013’ AND ’31-JUL-2013’; SELECT Merchandise.* FROM Merchandise LEFT JOIN JulyItems ON Merchandise.ItemID=JulyItems.ItemID WHERE JulyItems.Sale Is Null; The saved view forces the selection of July sale items to occur first. Then the LEFT JOIN applies those rows to the Merchandise table.

Subquery: Calculations 1 18 SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, SaleItem.SalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID WHERE Merchandise.Category=N’Cat’ AND SaleItem.SalePrice > 9; Query05_Fig12a Which cat merchandise sold for more than the average sale price of cat merchandise? If you know (guess) that the average price of cat merchandise is 9; then the query is easy. So write the easy part first.

Subquery: Calculations 2 19 Query05_Fig12b SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, SaleItem.SalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID WHERE Merchandise.Category=N’Cat’ AND SaleItem.SalePrice > 9; Which cat merchandise sold for more than the average sale price of cat merchandise? SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, SaleItem.SalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID WHERE Merchandise.Category=N’Cat’ AND SaleItem.SalePrice > (SELECT Avg(SaleItem.SalePrice) AS AvgOfSalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID WHERE Merchandise.Category=N’Cat’) ;

Subquery Calculation Notes 20 When building subqueries that use calculations: 1.Write the query using a simple number. 2.Write the subquery separately to compute the desired number. Test it! 3.Isolate the original estimated number in the first query by putting it on a separate line. 4.Delete the number and add parentheses ( ). 5.Paste the subquery inside the parentheses.

Subquery for Percentages 21 Query05_Fig13 Compute the merchandise sales by category in terms of percentage of total sales. SELECT Merchandise.Category, Sum([Quantity]*[SalePrice]) AS [Value], Sum([Quantity]*[SalePrice])/(SELECT Sum([Quantity]*[SalePrice]) FROM SaleItem) As [Pct] FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID GROUP BY Merchandise.Category; CategoryValuePercentage Bird$ E-02 Cat$1, Dog$4, Fish$1, Mammal$ E-02

Percentages with JOIN using Views 22 SELECT Category, Value, Value/MainTotal AS Percentage FROM CategorySubtotals, TotalItemSales; Save the first view that computes subtotals. Create a second view to compute totals. Compute the percentages in a third query using a cross join. CREATE VIEW TotalItemSales AS SELECT Sum(Value) AS MainTotal FROM CategorySubtotals; Query05_Fig14 CREATE VIEW CategorySubtotals AS SELECT Category, Sum(Quantity*SalePrice) AS Value FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID GROUP BY Merchandise.Category;

Sets of Data 23 List all of the customers who bought something in March and in May. Try answering this question the “easy” but wrong way. Query05_Fig15 SELECT Customer.CustomerID, Customer.Phone, Customer.LastName, Sale.SaleDate FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID WHERE Sale.SaleDate Between ’01-MAR-2013’ And ’31-MAR-2013’ AND Sale.SaleDate Between ’01-MAY-2013’ And ’31-MAY-2013’; The WHERE clause checks the date on each row to see if it fall in March AND in May. But no date can be in two months!

Two Sets using Subquery 24 SELECT Customer.LastName, Customer.FirstName FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID WHERE (SaleDate Between ’01-MAR-2013’ And ‘31-MAR-2013’) AND Customer.CustomerID IN (SELECT CustomerID FROM Sale WHERE (SaleDate Between ‘01-MAY-2013’ And ’31-MAY-2013’) ); List all of the customers who bought something in March and in May. Query05_Fig16 Customers in March and customers in May are two separate sets of data. Two separate SELECT statements are needed to answer the question. This query combines those sets using a subquery.

25 Two Sets of Data Using JOIN CREATE VIEW MarchCustomers AS SELECT CustomerID FROM Sale WHERE (SaleDate Between ‘01-MAR-2013’ And ‘31-MAR-2013’); CREATE VIEW MayCustomers AS SELECT CustomerID FROM Sale WHERE (SaleDate Between ‘1-MAY-2013’ And ‘31-MAY-2013’); SELECT Customer.LastName, Customer.FirstName FROM Customer INNER JOIN MarchCustomers ON Customer.CustomerID=MarchCustomers.CustomerID INNER JOIN MayCustomers ON MarchCustomers.CustomerID=MayCustomers.CustomerID;

Subquery: Any 26 Query05_Fig18 Any: value is compared to each item in the list. If it is True for any of the items, the statement is evaluated to True. Probably easier to use MIN function in the subquery. All: value is compared to each item in the list. If it is True for every item in the list, the statement is evaluated to True (much more restrictive than any. List dog merchandise with a list price greater than the sale price of the cheapest cat product. SELECT Merchandise.ItemID, Merchandise.Description, Merchandise.Category, Merchandise.ListPrice FROM Merchandise WHERE Category=N'Dog‘ AND ListPrice > ANY (SELECT SalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID=SaleItem.ItemID WHERE Merchandise.Category=N'Cat') ;

Subquery: All 27 Query05_Fig19 Has one salesperson made all of the sales on a particular day (Mar 28)? SELECT Employee.EmployeeID, Employee.LastName FROM Employee WHERE EmployeeID = ALL (SELECT EmployeeID FROM Sale WHERE SaleDate = #28-MAR-2013#) ; IDLastName 2Gibson Returns a match only if the employee made all of the sales on the specified date. (Or if there were no sales—all null values—on that date.)

Subquery: Exists 28 Use Not Exists to list customers who have not bought anything. SELECT Customer.CustomerID, Customer.Phone, Customer.LastName FROM Customer WHERE NOT EXISTS (SELECT SaleID, SaleDate FROM Sale WHERE Sale.CustomerID=Customer.CustomerID); EXISTS tests for the existence of rows in the subquery. The subquery can contain multiple columns because none of the returned values matter—only whether any values match the WHERE clause. This example is better if you use a JOIN command, but it works and illustrates the Exists term. Query05_Fig20

Correlated Subquery 29 Query05_Fig21 Which merchandise has a list price greater than the average sale price of merchandise within that category? SELECT Merchandise1.ItemID, Merchandise1.Description, Merchandise1.Category, Merchandise1.ListPrice FROM Merchandise AS Merchandise1 WHERE Merchandise1.ListPrice> ( SELECT Avg(SaleItem.SalePrice) AS AvgOfSalePrice FROM Merchandise As Merchandise2 INNER JOIN SaleItem ON Merchandise2.ItemID = SaleItem.ItemID WHERE Merchandise2.Category=Merchandise1.Category ); The WHERE clause in the subquery depends on values in the outer query. The tables require aliases to tell them apart.

Correlated Subquery Potential Problem 30  Assume small query  100,000 rows  5 categories of 20,000 rows  100,000 * 20,000 = 1 billion rows to read! 1Dog$ Dog$ Dog$ Dog$ Cat$ Cat$ Dog$4.00 8Cat$3.00 9Dog$7.50 Merchandise Compute Avg: $23.32 Compute Avg: $8.99 Recompute average for every row in the main query! MerchIDCategoryListPrice

More Efficient Solution: 2 queries 31  Compute the averages once and save query  JOIN saved query to main query  Two passes through table: 1 billion / 200,000 => 10,000 Bird$37.60 Cat$8.99 Dog$23.32 Fish$38.18 Mammal$9.00 CategoryAvgOfSalePrice Saved Query JOIN Merchandise.Category = Query05_Fig23a.Category Query05_Fig23a 1Dog$ Dog$ Dog$ Dog$ Cat$ Cat$ Dog$4.00 8Cat$3.00 9Dog$7.50 Merchandise MerchIDCategoryListPrice

Uncorrelated Queries 32 SELECT Merchandise.ItemID, Merchandise.Category, Merchandise.ListPrice, Query05_Fig23a.AvgOfSalePrice FROM Query05_Fig23a INNER JOIN Merchandise ON Query05_Fig23a.Category = Merchandise.Category WHERE Merchandise.ListPrice>[Query05_Fig23a].[AvgOfSalePrice]; SELECT Merchandise.Category, Avg(SaleItem.SalePrice) AS AvgOfSalePrice FROM Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID GROUP BY Merchandise.Category; Query05_Fig23b

UNION Operator 33 SELECT EID, Name, Phone, Salary, ‘East’ AS Office FROM EmployeeEast UNION SELECT EID, Name, Phone, Salary, ‘West’ AS Office FROM EmployeeWest EIDNamePhoneSalaryOffice 352Jones335245,000East 876Inez873647,000East 372Stoiko763238,000East 890Smythe980362,000West 361Kim773673,000West Offices in Los Angeles and New York. Each has an Employee table (East and West). Need to search data from both tables. Columns in the two SELECT lines must match.

UNION, INTERSECT, EXCEPT 34 T1T2 ABC SELECT EID, Name FROM EmployeeEast INTERSECT SELECT EID, Name FROM EmployeeWest List the name of any employee who has worked for both the East and West regions. T1 UNION T2A + B + C T1 INTERSECT T2B T1 EXCEPT T2A Microsoft Access supports only UNION. SQL Server supports all three.

Multiple JOIN Columns 35 AnimalID Name Category Breed DateBorn Gender... Category Breed Animal SELECT * FROM Breed INNER JOIN Animal ON Breed.Category = Animal.Category AND Breed.Breed = Animal.Breed Query05_Fig26 Sometimes need to JOIN tables on more than one column. PetStore: Category and Breed.

Reflexive Join 36 SELECT Employee.EmployeeID, Employee.LastName, Employee.ManagerID, E2.LastName FROM Employee INNER JOIN Employee AS E2 ON Employee.ManagerID = E2.EmployeeID EIDName...Manager 1Reeves11 2Gibson1 3Reasoner1 4Hopkins3 Employee EIDNameManagerName 1Reeves11Smith 2Gibson 1Reeves 3Reasoner 1Reeves SQL Result Query05_Fig20 Need to connect a table to itself. Common example: Employee(EID, LastName,..., ManagerID) A manager is also an employee. Use a second copy of the table and an alias.

37 Recursive Joins (SQL 99 and 2003) WITH RECURSIVE EmployeeList (EmployeeID, Title, Salary) AS ( SELECT EmployeeID, Title, 0.00 FROM Manages WHERE Title = N‘CEO’-- starting level UNION ALL SELECT Manages.EmployeeID, Manages.Title, Manages.Salary FROM EmployeeList INNER JOIN Manages ON EmployeeList.EmployeeID = Manages.ManagerID ) SELECT EmployeeID, Count(Title), Sum(Salary) FROM EmployeeList GROUP BY EmployeEID ; List all of the managers and list everyone who reports to them. Available in higher-end systems (SQL Server, Oracle, DB2, etc.), but each vendor uses a different, proprietary syntax. See the Workbooks. It provides tree spanning capabilities. Not available in Microsoft Access. Variations are in SQL Server and Oracle.

38 Recursive JOIN: SQL Server WITH DirectReports(EmployeeID, LastName, ManagerID, Title, Level) AS ( --Root/anchor member (find employee with no manager) SELECT EmployeeID, LastName, ManagerID, Title, 0 As Level FROM Employee WHERE ManagerID=0 -- starting level UNION ALL -- Recursive members SELECT Employee.EmployeeID, Employee.LastName, Employee.ManagerID, Employee.Title, Level +1 FROM Employee INNER JOIN DirectReports ON Employee.ManagerID = DirectReports.EmployeeID ) -- Now execute the common table expression SELECT ManagerID, EmployeeID, LastName, Title, Level FROM DirectReports ORDER BY Level, ManagerID, LastName

Recursive Query Results ManagerIDEmployeeIDLastNameTitleLevel 011SmithOwner0 111ReevesManager1 12GibsonManager2 13ReasonerManager2 26EatonAnimal Friend3 27FarrisAnimal Friend3 25JamesAnimal Friend3 29O’ConnorAnimal Friend3 210ShieldsAnimal Friend3 38CarpenterWorker3 34HopkinsWorker3 39

CASE Function 40 Select AnimalID, CASE WHEN Date()-DateBorn < 90 Then ‘Baby’ WHEN Date()-DateBorn >= 90 AND Date()-DateBorn < 270 Then ‘Young’ WHEN Date()-DateBorn >= 270 AND Date()-DateBorn < 365 Then ‘Grown’ ELSE ‘Experienced’ END FROM Animal; Not available in Microsoft Access. It is in SQL Server and Oracle. Example: Define age categories for the animals. Less than 3 months Between 3 months and 9 months Between 9 months and 1 year Over 1 year Convert age ranges into categories.

Inequality Join 41 AR(TransactionID, CustomerID, Amount, DateDue) LateCategory(Category, MinDays, MaxDays, Charge, …) Month30903% Quarter901205% Overdue % SELECT * FROM AR INNER JOIN LateCategory ON ((Date() - AR.DateDue) >= LateCategory.MinDays) AND ((Date() - AR.DateDue) < LateCategory.MaxDays) AccountsReceivable Categorize by Days Late 30, 90, 120+ Three queries? New table for business rules Classify payments by number of days late.

Queries with “Every” Need EXISTS 42 List the employees who have sold animals from every category. By hand: List the employees and the categories. Go through the SaleAnimal list and check off the animals they have sold.

Query With EXISTS 43 List the Animal categories where merchandise has not been sold by an employee (#5). SELECT Category FROM Category WHERE (Category <> 'Other') And Category NOT IN (SELECT Merchandise.Category FROM Merchandise INNER JOIN (Sale INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID) ON Merchandise.ItemID = SaleItem.ItemID WHERE Sale.EmployeeID = 5) If this query returns any rows, then the employee has not sold every animal. So list all the employees for whom the above query returns no rows: SELECT EmployeeID, LastName FROM Employee WHERE NOT EXISTS (above query slightly modified.) Query05_Fig31

44 Query for Every Query05_Fig32 SELECT Employee.EmployeeID, Employee.LastName FROM Employee WHERE Not Exists (SELECT Category FROM Category WHERE (Category NOT IN (‘Other’, ‘Reptile’, ‘Spider’) And Category NOT IN (SELECT Merchandise.Category FROM Merchandise INNER JOIN (Sale INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID) ON Merchandise.ItemID = SaleItem.ItemID WHERE Sale.EmployeeID = Employee.EmployeeID) ); EmployeeIDLastName 2Gibson 3Reasoner 5James 7Farris Which employees have merchandise sales from every category?

45 Simpler Query for Every Sometimes it is easier to use Crosstab and the Count function. But some systems do not have Crosstab, and sometimes the lists would be too long. So you need to know both techniques. Query05_Fig33 EIDLastNameBirdCatDogFishMammal 1Reeves Gibson Reasoner Hopkins James Eaton Farris Carpenter O'Connor Shields1 5 11Smith 1

SQL SELECT 46 SELECT DISTINCT Table.Column {AS alias},... FROM Table/Query {INNER or LEFT} JOIN Table/Query ON T1.ColA = T2.ColB WHERE (condition) GROUP BY Column HAVING (group condition) ORDER BY Table.Column { Union second select }

SQL Mnemonic 47 Someone From Ireland Will Grow Horseradish and Onions SELECT FROM INNER JOIN WHERE GROUP BY HAVING ORDER BY SQL is picky about putting the commands in the proper sequence. If you have to memorize the sequence, this mnemonic may be helpful.

SQL Data Definition  Create Schema Authorization dbName password  Create Table TableName (Column Type,...)  Alter Table Table {Add, Column, Constraint, Drop}  Drop {Table Table | Index Index On table}  Create Index IndexName ON Table (Column {ASC|DESC}) 48

Syntax Examples 49 CREATE TABLE Customer (CustomerID INTEGER NOT NULL, LastName VARCHAR (20), more columns ); ALTER TABLE Customer DROP COLUMN ZipCode; ALTER TABLE Customer ADD COLUMN CellPhone CHAR(15);

SQL: Foreign Key 50 CREATE TABLE Order (OrderID INTEGER NOT NULL, OrderDate DATE, CustomerID INTEGER CONSTRAINT pkorder PRIMARY KEY (OrderID), CONSTRAINT fkorder FOREIGN KEY (CustomerID) REFERENCES Customer (CustomerID) ); OrderID OrderDate CustomerID LastName FirstName Address … OrderCustomer *

SQL Data Manipulation Commands  Insert Into target (column1...) VALUES (value1...)  Insert Into target (column1...) SELECT... FROM...  Delete From table WHERE condition  Update table SET Column=Value,... Where condition  Note the use of the Select and Where conditions.  Synatx is the same--only learn it once.  You can also use subqueries. 51

Copy Old Customer Data 52 INSERT INTO OldCustomers SELECT * FROM Customer WHERE CustomerID IN (SELECT Sale.CustomerID FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID GROUP BY Sale.CustomerID HAVING Max(Sale.SaleDate)<’01-Jul-2013’) );

Delete Old Customer Data 53 DELETE FROM Customer WHERE CustomerID IN (SELECT Sale.CustomerID FROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID GROUP BY Sale.CustomerID HAVING Max(Sale.SaleDate)<’01-Jul-2013’) );

Update Example 54 UPDATE Merchandise SET ListPrice = ListPrice*1.10 WHERE Category = N‘Cat’ ; UPDATE Merchandise SET ListPrice = ListPrice*1.20 WHERE Category = N‘Dog’ ; Change the ListPrice of Merchandise at the PetStore. For cats, increase the ListPrice by 10%. For dogs, increase the ListPrice by 20%. Typically use two similar UPDATE statements. With the CASE function, the statements can be combined.

55 Quality: Building Queries  Break questions into smaller pieces.  Test each query.  Check the SQL.  Look at the data.  Check computations  Combine into subqueries.  Use cut-and-paste to avoid errors.  Check for correlated subqueries.  Test sample data.  Identify different cases.  Check final query and subqueries.  Verify calculations.  Test SELECT queries before executing UPDATE queries. Dogs and cat products on the same sale. Dogs and cat products at different times. Dogs and never any cat products. Cat products and never any dogs. Which customers who adopted Dogs also bought products for Cats (at any time)? Who adopted dogs? Who bought cat products?

56 Quality Queries: Example Which customers who adopted Dogs also bought products for Cats? SELECT DISTINCT Animal.Category, Sale.CustomerID FROM Sale INNER JOIN Animal ON Animal.SaleID = Sale.SaleID WHERE (Animal.Category='Dog') AND Sale.CustomerID IN ( SELECT DISTINCT Sale.CustomerID FROM Sale INNER JOIN (Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID) ON Sale.SaleID = SaleItem.SaleID WHERE (Merchandise.Category='Cat') ); A. Which customers adopted dogs? B. Which customers bought cat products? Query05_Fig38

Programming Review: Variables  Integer  2 bytes   Long  4 bytes  +/- 2,147,483,648  Single  4 bytes  +/ E 38  +/ E-45  Global, Const, Static  Double  8 bytes  +/ E 308  +/ E-324  Currency  8 bytes  +/- 922,337,203,685,  String & String*n  Variant  Any data type  Null 57

Programming: Scope and Lifetime  Scope  Where is the variable, and which procedures can access it?  Lifetime  When is the variable created, and when is it destroyed? 58 Form--Module Code Sub Button1_Click() Dim i1 As Integer i1 = 3 End Sub Sub Button2_Click() Dim i1 As Integer i1 = 7 End Sub Form Button1 Button2 Different procedures, different variables. Created and destroyed each time the button is clicked.

Programming: Global Variables  Wider scope and lifetime  Created at a higher level Form Public module  Accessible to any procedure in that form or module.  Declare it Global to make it available to any procedure. 59 Form--Module Code Sub Button2_Click() i2 = i2 + 7 End Sub Form Button1 Button2 Dim i2 As Integer Variable is created when form is opened. Clicking Button1 sets the initial value. Clicking Button2 modifies the value. What if user clicks buttons in a different order? Sub Button1_Click() i2 = 20 End Sub

Programming: Computations  Standard Math  + - * /  \ Integer divide  ^ Exponentiation (2^3 = 2*2*2 = 8)  Mod (15 Mod 4 = 3) ( = 15)  String  & Concatenation  Left, Right, Mid  Trim, LTrim, RTrim  String  Chr, Asc  LCase, UCase  InStr  Len  StrComp  Format 60 “Frank” & “Rose”  “FrankRose” Left(“Jackson”,5)  “Jacks” Trim(“ Maria “)  “Maria” Len(“Ramanujan”)  9 String(5,”a”)  “aaaaa” InStr(“8764 Main”,” “)  5

Programming: Standard Functions  Numeric  Exp, Log  Atn, Cos, Sin, Tan  Sqr  Abs  Sgn  Int, Fix  Rnd, Randomize 61 x = log e (e x ) Trigonometric functions  2 = Abs(-35)  35 Sgn(-35)  -1 Int(17.893)  17 Rnd()  ?  =30 92

Programming: Standard Functions: Date/Time 62  Date, Now, Time  DateAdd, DateDiff  “y”, “m”, “q”...  Firstweekday  1=Sunday,...  Can also be used to find number of Fridays, between two dates. todayDateDue 02/19/1003/21/10 DateDue = DateAdd(“d”, 30, Date())

Programming: Standard Functions: Variant  Variant  IsDate  IsNumeric  VarType  IsEmpty  IsNull 63

Programming: Debug  Stop  Ctrl-Break  F5: Go  F8: Step through  S-F8: Step over  Breakpoints  Immediate Window  ? or Print  Any assignment  Any code 64

Programming: Output: Message Box  MsgBox  Message  Type  Title  Types: Use Constants  vbOKOnlyvbOKCancel  vbAbortRetryIgnore  vbYesNoCancel  vbYesNovbRetryCancel  Defaults  vbDefaultButton1  vbDefaultButton2  vbDefaultButton3  Icons  vbCritical Stop sign  vbQuestion Question mark  vbExclamation Warning  vbInformation Circle i  Responses  vbOKvbCancel  vbAbortvbRetry  vbIgnore  vbYesvbNo 65 MsgBox "This is a message box", vbYesNoCancel + vbInformation, "Sample Box"

Programming: Input: InputBox  InputBox  Prompt  Title  Default  X-Pos, Y-Pos  Prompt  Cannot change box size  Use Chr(10) & Chr(13) for blank lines.  Returns text or Variant  Cancel = zero string ““  Positions  Twips  Twentieth of inch point  72 points  1440 twips per inch 66 Dim str As String str = InputBox( "Enter your name:", "Sample Input",, 5000, 5000)

Programming: Conditions  If  If (Condition) Then statements for true  Else statements for false  End If  IIF (Cond., True, False)  Select Case (expr)  Case value statements  Case value2  Case Else  End Select  Conditions , >=, =, <>  And, Or, Not, Xor  Eqv, Imp (logic) 67 If (Condition1) Then statements for true Else statements for false If (Condition2) Then statements for true End If

Programming Select Example 68  Message Box  Could use repeated If statements  Better to use Select Case response = MsgBox(…) If (response == vbYes) Then ‘ statements for Yes Else If (response == vbNo) Then ‘ statements for No Else ‘statements for Cancel End If response = MsgBox(…) Select Case response Case vbYes ‘ statements for Yes Case vbNo ‘ statements for No Case vbCancel ‘ statements for Cancel End Case

Programming: Loops  Do  For … Next  For Each 69 Do Until (x > 10) ‘ Statements x = x + 1 Loop Initialize value Statements Change value Test condition Do While (x <= 10) ‘ Statements x = x + 1 Loop Do ‘ Statements x = x + 1 Loop Until (x > 10) For x = 1 to 10 ‘ Statements Next x

Programming: Loops Again  Do  Do {While | Until} Exit Do (optional)  Loop  Do  Loop {While | Until}  For/Next  For counter = start To end Step increment Exit For (optional)  Next counter  For/Each (objects)  For Each element In group [Exit For] (optional)  Next element  With (objects)  With object  End With 70

Programming Subroutines and Functions  Sub name (var1 As..., var2,...)  End Sub  Function fname (var1 As...) As datatype  fname = … ‘ returns a specific value  End Function  Variables are passed by reference  Changes made to the parameters in the subroutine are passed back to the caller.  Unless you use ByVal  Changes are made to a copy of the parameter, but are not returned to the calling program. 71

Programming: Example Subroutine 72 Main program … StatusMessage “Trying to connect.” … StatusMessage “Verifying access.” … End main program Sub StatusMessage (Msg As String) ‘ Display Msg, location, color End Sub

Programming: Parameter Types 73 Main j = 3 DoSum j …‘ j is now equal to 8 Subroutine DoSum (j2 As Integer) j2 = 8 End Sub By Reference Changes to data in the subroutine are passed back. Main j = 3 DoSum j …‘ j is still equal to 3 Subroutine DoSum (ByVal j2 As Integer) j2 = 8 End Sub By Value Creates a copy of the variable, so changes are not returned.

Programming Arrays and User Types  Arrays  Dim array(sub,...) As type  Dim iSorts(10) As Integer  Specifying bounds:  (lower To upper,...)  ReDim [Preserve] array...  Option Base 0 | 1  v 2.0 arrays less than 64KB  User defined types  Type Tname ename1 As type ename2 As type  End Type  Dim var1 As Tname  var1.ename1 =...  var1.ename2 =... 74

Programming: Financial Functions  Fixed payments  PV (rate, nper, pmt, fv, due)  FV (rate, nper, pmt, pv, due)  IPmt (rate, per, nper, pv, fv, due)  NPer (rate, pmt, pv, fv, due)  Pmt (rate, nper, pv, fv,due)  PPmt (rate, per, nper, pv, fv, due)  Rate (nper, pmt, pv, fv, due, guess)  rate interest rate per period  per specific period number  nper # of periods  pv present value  fv future value  due 0=due at end, 1=due at start  Arrays  NPV (rate, array)  IRR (array, guess)  MIRR (array, finrate, re_rate)  Depreciation  DDB (cost, salv, life, period)  SLN (cost, salvage, life)  SYD (cost, salv., life, period) 75

Programming: Text File Input/Output  Open filename As # file#  Close # file#, Reset  Print #,Put, Write  Spc, Tab  Get, Input #, Line Input #  EOF, LOF  Seek # file#, position  ChDir, ChDirve  Dir  Kill, (re)Name  Lock, Unlock  CurDir, MkDir, RmDir 76

OLE: Object Linking & Embedding  CreateObject (class)  “appname. objecttype”  GetObject (file, class)  Methods and syntax are defined by the software that exports the object.  Example  Dim obj As Object  set obj = CreateObject(“Word.Basic”)  obj.Bold  obj.Insert “text”  obj.SaveAs “file” 77