+ All Categories
Home > Documents > Jerry Post Copyright © 2001 1 Database Management Systems Chapter 5 Advanced Queries.

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

Date post: 28-Dec-2015
Category:
Upload: jack-henderson
View: 218 times
Download: 0 times
Share this document with a friend
79
1 Jerry Post Copyright © 2001 Database Management Database Management Systems Systems Chapter 5 Advanced Queries
Transcript

1

Jerry PostCopyright © 2001

Database Management Database Management SystemsSystems

Chapter 5

Advanced Queries

2

DDAATTAABBAASSEE

Tables

SupplierIDNameContactNamePhoneAddressZipCodeCityID

Supplier

PONumberOrderDateReceiveDateSupplierIDEmployeeIDShippingCost

MerchandiseOrder

OrderIDOrderDateReceiveDateSupplierIDShippingCostEmployeeID

AnimalOrder

OrderIDAnimalIDCost

AnimalOrderItem

CityIDZipCodeCityStateAreaCodePopulation1990Population1980CountryLatitudeLongitude

City

EmployeeIDLastNameFirstNamePhoneAddressZipCodeCityIDTaxPayerIDDateHiredDateReleased

Employee

PONumberItemIDQuantityCost

OrderItem

CategoryRegistration

Category

CategoryBreed

Breed

AnimalIDNameCategoryBreedDateBornGenderRegisteredColorListPricePhoto

Animal

SaleIDSaleDateEmployeeIDCustomerIDSalesTax

Sale

SaleIDItemIDQuantitySalePrice

SaleItem

ItemIDDescriptionQuantityOnHandListPriceCategory

Merchandise

SaleIDAnimalIDSalePrice

SaleAnimal

CustomerIDPhoneFirstNameLastNameAddressZipCodeCityID

Customer

3

DDAATTAABBAASSEE

Organization

Harder Questions Subqueries Not In, LEFT JOIN UNION, Multiple JOIN columns, Recursive JOIN Other SQL Commands

DDL: Data Definition LanguageDML: Data Manipulation Language

OLAPMicrosoft SQL ServerOracleMicrosoft Access Crosstab

4

DDAATTAABBAASSEE

Harder Questions

How many cats are “in-stock” on 10/1/01?

Which cats sold for more than the average price?

Which animals sold for more than the average price of animals in their category?

Which animals have not been sold?

Which customers (who bought something at least once) did not buy anything between 11/1/01 and 12/31/01?

Which customers who bought Dogs also bought products for Cats (at any time)?

5

DDAATTAABBAASSEE

Sub-query for Calculation Which cats sold for more than the average sale price of cats?

Assume we know the average price is $170. Usually we need to compute it first.

SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePriceFROM AnimalINNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalIDWHERE ((Animal.Category="Cat") AND (SaleAnimal.SalePrice>170));

SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePriceFROM AnimalINNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalIDWHERE ((Animal.Category="Cat") AND (SaleAnimal.SalePrice> ( SELECT AVG(SalePrice)

FROM AnimalINNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalIDWHERE (Animal.Category=“Cat”)

) ) );

6

DDAATTAABBAASSEE

Query Sets (IN)

List all customers (Name) who purchased one of the following items: 1, 2, 30, 32, 33.

SELECT Customer.LastName, Customer.FirstName, SaleItem.ItemIDFROM (Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID) INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleIDWHERE (SaleItem.ItemID In (1,2,30,32,33))ORDER BY Customer.LastName, Customer.FirstName;

Could use Or, but harder to write.

In ( . . .) matches any in the list.

Query04_13

7

DDAATTAABBAASSEE

Using IN with a Sub-query

List all customers who bought items for cats.

SELECT Customer.LastName, Customer.FirstName, SaleItem.ItemIDFROM (Customer

INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerID)INNER JOIN SaleItem ON Sale.SaleID = SaleItem.SaleID

WHERE (SaleItem.ItemID In(SELECT ItemID FROM Merchandise WHERE Category="Cat"));

8

DDAATTAABBAASSEE

SubQuery (IN: Look up a Set)

List all of the customers who bought something in March and who bought something in May. (Two tests on the same data!)

LastName First Adkins Inga McCain Sam Grimes Earl

SELECT Customer.LastName, Customer.FirstNameFROM Customer INNER JOIN Sale ON Customer.CustomerID = Sale.CustomerIDWHERE ((Month([SaleDate])=3)) And Customer.CustomerID In (SELECT CustomerID FROM Sale WHERE (Month([SaleDate])=5) );

Query04_14

9

DDAATTAABBAASSEE

SubQuery (ANY, ALL)

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.

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.

SELECT DISTINCTROW Animal.AnimalID, Name, SalePrice, ListPriceFROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalIDWHERE (((SalePrice) > Any

(SELECT 0.80*ListPrice FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE Category = "Cat"))

AND ((Category)="Cat"));

Query04_15

10

DDAATTAABBAASSEE

SubQuery: NOT IN (Subtract)

Which animals have not been sold? Start with list of all animals. Subtract out list of those who were sold.

AnimalID NameCategory

12 Leisha Dog 19 Gene Dog 25 Vivian Dog 34 Rhonda Dog 88 Brandy Dog 181 Fish

SELECT Animal.AnimalID, Animal.Name, Animal.CategoryFROM AnimalWHERE (Animal.AnimalID Not In (SELECT AnimalID From SaleAnimal));

Query04_16

11

DDAATTAABBAASSEE

SubQuery: NOT IN (Data)

ID Name Category Breed2 Fish Angel4 Gary Dog Dalmation5 Fish Shark6 Rosie Cat Oriental Shorthair7 Eugene Cat Bombay8 Miranda Dog Norfolk Terrier9 Fish Guppy

10 Sherri Dog Siberian Huskie11 Susan Dog Dalmation12 Leisha Dog Rottweiler

ID SaleID SalePrice2 35 $10.804 80 $156.666 27 $173.997 25 $251.598 4 $183.38

10 18 $150.1111 17 $148.47

Animal SaleAnimal

Which animals have not been sold?

12

DDAATTAABBAASSEE

Left Outer Join

Which animals have not been sold? LEFT JOIN includes all rows from left table (Animal)

But only those from right table (SaleAnimal) that match a row in Animal. Rows in Animal without matching data in Sale Animal will have Null.

SELECT Animal.AnimalID, Animal.Name, Animal.CategoryFROM Animal LEFT JOIN SaleAnimalON Animal.AnimalID = SaleAnimal.AnimalIDWHERE (SaleAnimal.SaleID Is Null);

AnimalID NameCategory

12 Leisha Dog 19 Gene Dog 25 Vivian Dog 34 Rhonda Dog 88 Brandy Dog 181 Fish

Query04_17

13

DDAATTAABBAASSEE

Left Outer Join (Example)

ID Name Category Breed2 Fish Angel4 Gary Dog Dalmation5 Fish Shark6 Rosie Cat Oriental Shorthair7 Eugene Cat Bombay8 Miranda Dog Norfolk Terrier9 Fish Guppy

10 Sherri Dog Siberian Huskie11 Susan Dog Dalmation12 Leisha Dog Rottweiler

ID SaleID SalePrice2 35 $10.804 80 $156.66

Null Null Null6 27 $173.997 25 $251.598 4 $183.38

Null Null Null10 18 $150.1111 17 $148.47

Null Null Null

14

DDAATTAABBAASSEE

Older Syntax for Left Join

Which animals have not been sold?

SELECT ALL

FROM Animal, SaleAnimal

WHERE Animal.AnimalID *= SaleAnimal.AnimalID

And SaleAnimal.SaleID Is Null;

SELECT ALL

FROM Animal, SaleAnimal

WHERE Animal.AnimalID = SaleAnimal.AnimalID (+)

And SaleAnimal.SaleID Is Null;

Oracle syntax--note that the (+) symbol is on the reversed side.

15

DDAATTAABBAASSEE

SubQuery for Computation

Don’t know the average, so use a subquery to look it up.

Watch parentheses.

Query04_18

SELECT SaleAnimal.AnimalID, Animal.Category, SaleAnimal.SalePriceFROM AnimalINNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalIDWHERE ((Animal.Category="Cat") AND (SaleAnimal.SalePrice> ( SELECT AVG(SalePrice)

FROM AnimalINNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalIDWHERE (Animal.Category=“Cat”) ) ) );

16

DDAATTAABBAASSEE

Correlated Subquery

SELECT AnimalID, Name, Category, SalePriceFROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalIDWHERE (SaleAnimal.SalePrice> (SELECT Avg(SaleAnimal.SalePrice) FROM Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID WHERE (Animal.Category = Animal.Category) ) )ORDER BY SaleAnimal.SalePrice DESC;

List the Animals that have sold for a price higher than the average for animals in that Category.

The subquery needs to compute the average for a given category.

Problem: Which category? Answer: the category that matches the category from the main

part of the query. Problem: How do we refer to it? Both tables are called Animal.

This query will not work yet.

17

DDAATTAABBAASSEE

Correlated SubQuery (Avoid)

List the Animals that have sold for a price higher than the average for animals in that Category.

Match category in subquery with top level Rename tables (As)

Correlated Subquery Recompute subquery for

every row in top level--slow!

Better to compute and save Subquery, then use in join.

SELECT A1.AnimalID, A1.Name, A1.Category, SaleAnimal.SalePriceFROM Animal As A1 INNER JOIN SaleAnimal ON A1.AnimalID = SaleAnimal.AnimalIDWHERE (SaleAnimal.SalePrice> (SELECT Avg(SaleAnimal.SalePrice) FROM Animal As A2 INNER JOIN SaleAnimal ON A2.AnimalID = SaleAnimal.AnimalID WHERE (A2.Category = A1.Category) ) )ORDER BY SaleAnimal.SalePrice DESC;

Query04_19

18

DDAATTAABBAASSEE

Correlated Subquery Problem

Fish $10.80Dog $156.66Fish $19.80Cat $173.99Cat $251.59Dog $183.38Fish $1.80Dog $150.11Dog $148.47

Category SalePrice

Animal + SaleAnimal

Compute Avg: $37.78Compute Avg: $174.20Compute Avg: $37.78Compute Avg: $169.73Compute Avg: $169.73

Recompute average for every row in the main query!

Assume small query 100,000 rows 5 categories of 20,000 rows

100,000 * 20,000 = 1 billion rows to read!

19

DDAATTAABBAASSEE

More Efficient Solution: 2 queries

Compute the averages once and save query JOIN saved query to main query Two passes through table: 1 billion / 200,000 => 10,000

Fish $10.80Dog $156.66Fish $19.80Cat $173.99Cat $251.59Dog $183.38Fish $1.80Dog $150.11Dog $148.47

Category SalePrice

Animal + SaleAnimal

Bird $176.57Cat $169.73Dog $174.20Fish $37.78Mammal $80.72Reptile $181.83Spider $118.16

Category AvgOfSalePrice

Saved Query

JOIN

Animal.Category = Query1.Category

20

DDAATTAABBAASSEE

UNION Operator

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.

SELECT EID, Name, Phone, Salary, ‘East’ AS OfficeFROM EmployeeEastUNIONSELECT EID, Name, Phone, Salary, ‘West’ AS OfficeFROM EmployeeWest

EID Name Phone Salary Office352 Jones 3352 45,000 East876 Inez 8736 47,000 East372 Stoiko 7632 38,000 East

890 Smythe 9803 62,000 West361 Kim 7736 73,000 West

21

DDAATTAABBAASSEE

UNION, INTERSECT, EXCEPT

T1 T2

A B C

SELECT EID, NameFROM EmployeeEastINTERSECTSELECT EID, NameFROM EmployeeWest

List the name of any employee who has worked for both the East and West regions.

22

DDAATTAABBAASSEE

Multiple JOIN Columns

Sometimes need to JOIN tables on more than one column. PetStore: Category and Breed.

AnimalIDNameCategoryBreedDateBornGender. . .

CategoryBreed

Breed

Animal

SELECT *FROM Breed INNER JOIN AnimalON Breed.Category = Animal.CategoryAND Breed.Breed = Animal.Breed

23

DDAATTAABBAASSEE

Reflexive Join

Need to connect a table to itself. Common example: Employee(EID, Name, . . ., Manager)

A manager is also an employee. Use a second copy of the table and an alias.

SELECT Employee.EID, Employee.Name, Employee.Manager, E2.Name

FROM Employee INNER JOIN Employee AS E2

ON Employee.Manager = E2.EID

EID Name . . . Manager115 Sanchez 765462 Miller 115523 Hawk 115765 Munoz 886

Employee

EID Name Manager Name115 Sanchez 765 Munoz462 Miller 115 Sanchez523 Hawk 115 Sanchez

SQL

Result

24

DDAATTAABBAASSEE

CASE Function

Used to change data to a different context. 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

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”

ENDFROM Animal;

Not available in Microsoft Access. It is in SQL Server and Oracle.

25

DDAATTAABBAASSEE

Inequality Join

AR(TransactionID, CustomerID, Amount, DateDue)

AccountsReceivable Categorize by Days Late

30, 90, 120+

Three queries? New table for business rules

LateCategory(Category, MinDays, MaxDays, Charge, …)

Month 30 90 3%Quarter 90 120 5%Overdue 120 9999 10%

SELECT *FROM AR INNER JOIN LateCategory ON ((Date() - AR.DateDue) >= LateCategory.MinDays) AND ((Date() - AR.DateDue) < LateCategory.MaxDays)

26

DDAATTAABBAASSEE

SQL SELECT

SELECT DISTINCT Table.Column {AS alias} , . . .FROM Table/QueryINNER JOIN Table/Query ON T1.ColA = T2.ColBWHERE (condition)GROUP BY ColumnHAVING (group condition)ORDER BY Table.Column{ Union second select }

TRANSFORM aggfunction {Crosstab values}SELECT . . . FROM . . . GROUP BY {Crosstab rows}PIVOT pivotfield {Crosstab columns}

27

DDAATTAABBAASSEE

SQL Mnemonic

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.

28

DDAATTAABBAASSEE

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})

29

DDAATTAABBAASSEE

Syntax Examples

CREATE TABLE Customer

(CustomerID INTEGER NOT NULL,

LastName CHAR (10),

more columns

);

ALTER TABLE Customer

DROP COLUMN ZipCode;

ALTER TABLE Customer

ADD COLUMN CellPhone CHAR(15);

30

DDAATTAABBAASSEE

Queries with “Every” Need EXISTSList 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.

31

DDAATTAABBAASSEE

Query With EXISTSList the Animal categories that have not been sold by an employee (#5).

SELECT CategoryFROM Category WHERE (Category <> "Other") And Category NOT IN (SELECT Animal.Category FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal ON Sale.SaleID = SaleAnimal.SaleID) ON Animal.AnimalID = SaleAnimal.AnimalID 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.)

32

DDAATTAABBAASSEE

Query for Every

SELECT Employee.EmployeeID, Employee.LastNameFROM EmployeeWHERE Not Exists (SELECT Category FROM Category WHERE (Category <> "Other") And Category NOT IN (SELECT Animal.Category FROM Animal INNER JOIN (Sale INNER JOIN SaleAnimal ON Sale.SaleID = SaleAnimal.SaleID) ON Animal.AnimalID = SaleAnimal.AnimalID WHERE Sale.EmployeeID = Employee.EmployeeID) );

Result: 3 Reasoner

33

DDAATTAABBAASSEE

Simpler Query for EverySometimes it is easier to use Crosstab and the Count function.

But some systems do not have Crosstab, and sometimes thelists would be too long. So you need to know both techniques.

34

DDAATTAABBAASSEE

SQL: Foreign KeyCREATE TABLE Order

(OrderID INTEGER NOT NULL,

OrderDate DATE,

CustomerID INTEGER

CONSTRAINT pkorder PRIMARY KEY (OrderID),

CONSTRAINT fkorder FOREIGN KEY (CustomerID)

REFERENCES Customer (CustomerID)

);

OrderIDOrderDateCustomerID

CustomerIDLastNameFirstNameAddress…

Order Customer

*

35

DDAATTAABBAASSEE

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.

36

DDAATTAABBAASSEE

Copy Old Animal DataINSERT INTO OldAnimalsSELECT *FROM AnimalsWHERE AnimalID IN

(SELECT AnimalOrderItem.AnimalID

FROM AnimalOrder INNER JOIN AnimalOrderItem

ON AnimalOrder.OrderID = AnimalOrderItem.OrderId

WHERE (AnimalOrder.OrderDate<#1/1/01#) );

37

DDAATTAABBAASSEE

Delete Old Animal DataDELETEFROM AnimalsWHERE AnimalID IN

(SELECT AnimalOrderItem.AnimalID

FROM AnimalOrder INNER JOIN AnimalOrderItem

ON AnimalOrder.OrderID = AnimalOrderItem.OrderId

WHERE (AnimalOrder.OrderDate<#1/1/01#) );

38

DDAATTAABBAASSEE

Update Example

Change the ListPrice of Animals 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.

UPDATE Animal

SET ListPrice = ListPrice*1.10

WHERE Category = “Cat” ;

UPDATE Animal

SET ListPrice = ListPrice*1.20

WHERE Category = “Dog” ;

39

DDAATTAABBAASSEE

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. 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 bought Dogsalso bought products for Cats(at any time)?

Who bought dogs?Who bought cat products?

Test SELECT queriesbefore executingUPDATE queries.

40

DDAATTAABBAASSEE

Quality Queries: ExampleWhich customers who bought Dogs also bought products for Cats?

SELECT DISTINCT Animal.Category, Sale.CustomerIDFROM Sale INNER JOIN (Animal INNER JOIN SaleAnimal ON Animal.AnimalID = SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleIDWHERE (((Animal.Category)="Dog"))

SELECT DISTINCT Sale.CustomerIDFROM Sale INNER JOIN (Merchandise INNER JOIN SaleItem ON Merchandise.ItemID = SaleItem.ItemID) ON Sale.SaleID = SaleItem.SaleIDWHERE (((Merchandise.Category)="Cat"))

A. Which customers bought dogs?B. Which customers bought cat products?

AND Sale.CustomerID IN (

);

41

DDAATTAABBAASSEE

Data Warehouse

OLTP Database3NF tables

Operationsdata

Predefinedreports

Data warehouseStar configuration

Daily datatransfer

Interactivedata analysis

Flat files

42

DDAATTAABBAASSEE

Data Warehouse Goals

Existing databases optimized for Online Transaction Processing (OLTP)

Online Analytical Processing (OLAP) requires fast retrievals, and only bulk writes.

Different goals require different storage, so build separate data warehouse to use for queries.

Extraction, Transformation, Transportation (ETT) Data analysis

Ad hoc queries Statistical analysis Data mining (specialized automated tools)

43

DDAATTAABBAASSEE

OLTP v. OLAP

44

DDAATTAABBAASSEE

Multidimensional Cube

TimeSale Date

CustomerLocation

Categ

ory

Pet StoreItem SalesAmount = Quantity*Sale Price

45

DDAATTAABBAASSEE

Sales Date: Time Hierarchy

Year

Quarter

Month

Week

Day

Levels Roll-upTo get higher-level totals

Drill-downTo get lower-level details

46

DDAATTAABBAASSEE

Star Design

SalesQuantity

Amount=SalePrice*Quantity

Fact Table

Products

CustomerLocation

Sales Date

Dimension Tables

47

DDAATTAABBAASSEE

Snowflake Design: SQL Server Analysis

48

DDAATTAABBAASSEE

OLAP Computation Issues

Compute Quantity*Price in base query, then add to get $23.00

If you use Calculated Measure in the Cube, it will add first and multiply second to get $45.00, which is wrong.

49

DDAATTAABBAASSEE

SQL Server Analysis Cube DesignDefine the Data Source (choose the database)Create a new cube—avoid the wizard

Create the OLAPItems query, Amount=Quantity*SalePricePick the fact table: OLAPItems queryCreate a new dimension: PetItemSaleDate

Star designSale table, SaleDate column, Time dimension

Create a second dimension: PetItemCategoryStarMerchandise table, Category column

Create a third dimension: PetCustomerLocationSnowflakeSale, Customer, City tablesCountry, State, City columns

Select the data to measure in the fact tableMeasures, New: Quantity, Amount

Save the cube as: PetItemSalesProcess the cube (icon)

MOLAP (stores data in a cube layout)Select the defaults on the other options.

50

DDAATTAABBAASSEE

Oracle OLAP DesignCREATE MATERIALIZED VIEW OLAPITEMS BUILD IMMEDIATE REFRESH ON DEMAND AS SELECT SaleID, ItemID, Quantity, Quantity*SalePrice AS Amount FROM SaleItem; CREATE MATERIALIZED VIEW PETSALEDATE BUILD IMMEDIATE REFRESH ON DEMAND AS SELECT SaleID, TO_CHAR(SaleDate,'yyyy') AS SaleYear, TO_CHAR(SaleDate,'yyyy') || '-' || TO_CHAR(SaleDate,'Q') AS SaleQuarter, TO_CHAR(SaleDate,'yyyy') || '-' || TO_CHAR(SaleDate, 'mm') AS SaleMonth, TO_CHAR(SaleDate,'yyyy') || '-' || TO_CHAR(SaleDate, 'ww') AS SaleWeek, SaleDate FROM Sale;

Create snapshots (Materialized Views) to preprocess queries.Mostly an issue of performance—use Star and bitmap indexes.Need Oracle Express ($$$$$) or have to build tables yourself.

51

DDAATTAABBAASSEE

SQL Server OLAP Data Browsing

52

DDAATTAABBAASSEE

Microsoft Pivot Table

53

DDAATTAABBAASSEE

Excel Pivot Table Reports

Can place data in rows or columns.By grouping months, can instantly get quarterly or monthly totals.Will have to reconnect to the database: PetStore2000.mdbAnd the query: qryPivotExample

Quarter MonthQuarter 1 Quarter 2 Quarter 3 Quarter 4 Grand Total

LastName EmployeeIDDataCarpenter 8 Sum of Animal 1,668.91 606.97 426.39 7.20 2,709.47

Sum of Merchandise 324.90 78.30 99.00 128.70 630.90Eaton 6 Sum of Animal 522.37 341.85 562.50 1,426.72

Sum of Merchandise 30.60 54.90 107.10 192.60Farris 7 Sum of Animal 5,043.36 1,059.70 796.47 6,899.53

Sum of Merchandise 826.92 188.10 306.00 1,321.02Gibson 2 Sum of Animal 4,983.51 1,549.83 2,556.10 9,089.44

Sum of Merchandise 668.25 238.50 450.90 1,357.65Hopkins 4 Sum of Animal 3,747.96 1,194.88 372.65 128.41 5,443.90

Sum of Merchandise 476.91 252.90 121.50 7.20 858.51James 5 Sum of Animal 3,282.77 2,373.08 437.88 150.11 6,243.84

Sum of Merchandise 505.89 693.45 99.00 99.00 1,397.34O'Connor 9 Sum of Animal 2,643.69 180.91 510.12 3,334.72

Sum of Merchandise 263.70 83.70 55.80 403.20Reasoner 3 Sum of Animal 4,577.43 625.74 589.68 2,500.24 8,293.09

Sum of Merchandise 762.30 89.10 116.80 396.90 1,365.10Reeves 1 Sum of Animal 1,120.93 1,120.93

Sum of Merchandise 263.88 263.88Shields 10 Sum of Animal 1,008.76 162.15 1,170.91

Sum of Merchandise 62.10 22.50 84.60Total Sum of Animal 28,599.69 7,591.11 2,840.72 6,701.03 45,732.55Total Sum of Merchandise 4,185.45 1,624.05 569.50 1,495.80 7,874.80

54

DDAATTAABBAASSEE

Oracle OLAP Browser

SELECT DECODE (GROUPING(SaleMonth), 1, 'All months', SaleMonth) AS Month, DECODE (GROUPING(Category), 1, 'All categories', Category) AS Category, SUM(Amount) AS AmountTotal FROM PetSaleDate, OLAPItems, Merchandise WHERE PetSaleDate.SaleID = OLAPItems.SaleID AND OLAPItems.ItemID=Merchandise.ItemID GROUP BY ROLLUP (SaleMonth, Category); SELECT DECODE (GROUPING(SaleMonth), 1, 'All months', SaleMonth) AS Month, DECODE (GROUPING(Category), 1, 'All categories', Category) AS Category, SUM(Amount) AS AmountTotal FROM PetSaleDate, OLAPItems, Merchandise WHERE PetSaleDate.SaleID = OLAPItems.SaleID AND OLAPItems.ItemID=Merchandise.ItemID GROUP BY CUBE (SaleMonth, Category);

DECODE … GROUPING assigns titles to the totals

55

DDAATTAABBAASSEE

Oracle OLAP QueryMONTH CATEGORY AMOUNTTOTAL ---------- --------------------------------- ----------- 2001-01 Bird 135 2001-01 Cat 396 2001-01 Dog 509.22 2001-01 Fish 300.6 2001-01 Mammal 18 2001-01 All categories 1358.82 2001-02 Bird 45 2001-02 Cat 113.85 2001-02 Dog 927.09 2001-02 Fish 414 2001-02 Mammal 9 2001-02 All categories 1508.94 … … … All months All categories 8448.19

MONTH CATEGORY AMOUNTTOTAL ---------- ------------------------------------ ----------- 2001-01 Bird 135 2001-01 Cat 396 2001-01 Dog 509.22 2001-01 Fish 300.6 2001-01 Mammal 18 2001-01 All categories 1358.82 2001-02 Bird 45 2001-02 Cat 113.85 2001-02 Dog 927.09 2001-02 Fish 414 2001-02 Mammal 9 2001-02 All categories 1508.94 … … … All months Bird 607.5 All months Cat 1289.7 All months Dog 4863.49 All months Fish 1597.5 All months Mammal 90 All months All categories 8448.19

ROLLUP (left) computes totals only as specified.

CUBE (right) computes all totals.

56

DDAATTAABBAASSEE

Microsoft Access Crosstab Result

Month Bird Cat Dog Fish Mammal Reptile Spider

1 $217.51 $1,655.01

2 $324.87 $597.74 $1,281.81 $39.60 $127.78

3 $364.18 $198.85 $650.17 $378.25 $40.50

4 $334.50 $1,221.10 $172.88

5 $396.84 $335.48 $1,192.56 $126.20

6 $119.71 $459.91 $1,607.46 $5.40 $19.80

7 $573.60 $1,644.73 $319.07 $19.80 $182.31

8 $578.35 $1,444.75 $1,859.71 $27.90 $320.52

9 $538.07 $792.46 $1,219.03

10 $173.50 $942.89 $1,429.27 $10.80 $11.70 $229.73 $313.97

11 $153.07 $1,308.97 $1,784.06 $112.50

12 $770.87 $1,178.47

57

DDAATTAABBAASSEE

Crosstab

Total animal sales by Category for each month.

TRANSFORM Sum(SaleAnimal.SalePrice) AS SumOfSalePriceSELECT Month([Sale].[SaleDate]) AS SaleMonthFROM Sale INNER JOIN (Animal INNER JOIN SaleAnimalON Animal.AnimalID = SaleAnimal.AnimalID) ON Sale.SaleID = SaleAnimal.SaleIDGROUP BY Month([Sale].[SaleDate])PIVOT Animal.Category;

Query04_20

58

DDAATTAABBAASSEE

Programming Review: Variables

Integer 2 bytes -32768 32767

Long 4 bytes +/- 2,147,483,648

Single 4 bytes +/- 3.402823 E 38 +/- 1.401298 E-45

Global, Const, Static

Double 8 bytes +/- 1.79769313486232 E 308 +/- 4.94065645841247 E-324

Currency 8 bytes +/- 922,337,203,685,477.5808

String & String*n Variant

Any data type Null

59

DDAATTAABBAASSEE

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?

Form--Module Code

Sub Button1_Click()Dim i1 As Integeri1 = 3End Sub

Sub Button2_Click()Dim i1 As Integeri1 = 7End Sub

FormButton1Button1Button2Button2

Different procedures,different variables.Created and destroyedeach time the buttonis clicked.

60

DDAATTAABBAASSEE

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.

Form--Module Code

Sub Button2_Click()i2 = i2 + 7End Sub

FormButton1Button1Button2Button2

Dim i2 As Integer

Variable is created whenform is opened.Clicking Button1 sets theinitial value.Clicking Button2 modifiesthe value.What if user clicks buttons in a different order?

Sub Button1_Click()i2 = 20End Sub

61

DDAATTAABBAASSEE

Programming: Computations Standard Math

+ - * / \ Integer divide ^ Exponentiation

(2^3 = 2*2*2 = 8)

Mod (15 Mod 4 = 3) (12 + 3 = 15)

String & Concatenation Left, Right, Mid Trim, LTrim, RTrim String Chr, Asc LCase, UCase InStr Len StrComp Format

“Frank” & “Rose” “FrankRose”

Left(“Jackson”,5) “Jacks”

Trim(“ Maria “) “Maria”

Len(“Ramanujan”) 9

String(5,”a”) “aaaaa”

InStr(“8764 Main”,” “) 5

62

DDAATTAABBAASSEE

Programming: Standard Functions

Numeric Exp, Log Atn, Cos, Sin, Tan Sqr Abs Sgn Int, Fix Rnd, Randomize

x = loge (ex)

Trigonometric functions2 = 1.414

Abs(-35) 35

Sgn(-35) -1

Int(17.893) 17

Rnd() 0.198474

? =3092

63

DDAATTAABBAASSEE

Programming:Standard Functions: Date/Time

Date, Now, Time DateAdd, DateDiff

“y”, “m”, “q” . . . Firstweekday 1=Sunday,. . . Can also be used

to find number of Fridays, between two dates.

today DateDue

02/19/01 03/21/01

DateDue = DateAdd(“d”, 30, Date())

64

DDAATTAABBAASSEE

Programming:Standard Functions: Variant

Variant IsDate IsNumeric VarType IsEmpty IsNull

65

DDAATTAABBAASSEE

Programming: Debug

Stop Ctrl-Break F5: Go F8: Step through S-F8: Step over Breakpoints

Immediate Window ? or Print Any assignment Any code

66

DDAATTAABBAASSEE

Programming:Output: Message Box MsgBox

Message Type Title

Types: Use Constants vbOKOnly

vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo

vbRetryCancel Defaults

vbDefaultButton1 vbDefaultButton2 vbDefaultButton3

Icons vbCritical Stop sign vbQuestion Question mark vbExclamation Warning vbInformation Circle i

Responses vbOK vbCancel vbAbort vbRetry vbIgnore vbYes vbNo

MsgBox "This is a message box", vbYesNoCancel + vbInformation, "Sample Box"

67

DDAATTAABBAASSEE

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

Dim str As Stringstr = InputBox( "Enter your name:", "Sample Input", , 5000, 5000)

68

DDAATTAABBAASSEE

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)

If (Condition1) Thenstatements for true

Elsestatements for falseIf (Condition2) Then

statements for trueEnd If

End If

69

DDAATTAABBAASSEE

ProgrammingSelect Example Message Box

Could use repeated If statements

Better to use Select Case

response = MsgBox(…)If (response == vbYes) Then

‘ statements for YesElse

If (response == vbNo) Then‘ statements for No

Else ‘statements for Cancel

End IfEnd If

response = MsgBox(…) Select Case response

Case vbYes‘ statements for Yes

Case vbNo‘ statements for No

Case vbCancel‘ statements for Cancel

End Case

70

DDAATTAABBAASSEE

Programming: Loops

Do For … Next For Each

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

71

DDAATTAABBAASSEE

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

72

DDAATTAABBAASSEE

ProgrammingSubroutines 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.

73

DDAATTAABBAASSEE

Programming: Example Subroutine

Main program…StatusMessage “Trying to connect.”…StatusMessage “Verifying access.”… End main program

Sub StatusMessage (Msg As String)‘ Display Msg, location, color

End Sub

74

DDAATTAABBAASSEE

Programming: Parameter TypesMainj = 3DoSum j… ‘ j is now equal to 8

Subroutine DoSum (j2 As Integer)j2 = 8

End Sub

By ReferenceChanges to data in thesubroutine are passed back.

Mainj = 3DoSum j… ‘ j is still equal to 3

Subroutine DoSum (ByVal j2 As Integer)j2 = 8

End Sub

By ValueCreates a copy of thevariable, so changes arenot returned.

75

DDAATTAABBAASSEE

ProgrammingArrays 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 = . . .

76

DDAATTAABBAASSEE

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)

77

DDAATTAABBAASSEE

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

78

DDAATTAABBAASSEE

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”

79

DDAATTAABBAASSEE

DDE: Dynamic Data Exchange

Shell DDEInitiate DDEExecute DDEPoke, DDE Send

Send data

DDE, DDERequest Request data

DDETerminate

Application must be running Start a conversation/topic Issue a command Place data

Get data

Close the session


Recommended