sql training oracle sql functions. confidential & proprietary copyright © 2009 cardinal...

31
SQL Training ORACLE SQL Functions

Upload: cathleen-atkinson

Post on 29-Dec-2015

236 views

Category:

Documents


0 download

TRANSCRIPT

SQL Training

ORACLE SQL Functions

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Lesson Objectives

• Write SQL Statements using:

– Aggregate Functions (max, min, avg)

– Common CHAR and DATE functions

Page 2

At the end of this section you will be able to:

Aggregate Functions

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Select – Aggregate FunctionsThe following aggregate functions can be applied to multiple values retrieved from a table.

Function Purpose

MIN Yields the minimum value in a column

MAX Yields the maximum value in a column

AVG Computes the average value for a column

SUM Computes the total value for a column

COUNT Lists the number of rows in a query, or lists the number of distinct column values

Page 4

Group By and Having

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Group By

Page 6

Show the number of components used to build ProductCode HG4000-01C (ProductID = 15)

SELECT Product.ProductID, Product.ProductDescription,

Sum(RequiredQTY) as NumComponentsFrom Product, ManifestWhere Product.ProductID = Manifest.ProductID and

Product.ProductID = 15Group By Product.ProductID, Product.ProductDescription;

PRODUCTID PRODUCTDESCRIPTION NUMCOMPONENTS

15 HomeGen 4000 - Natural Gas, 240v 60Hz

43

All fields in the SELECT clause that are not part of an aggregate function must be included in the GROUP BY clause.

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Group ByProblem: How many vendors are in each country? Show by Country and Region.

SELECT c.countryname, r.regionname,

count(vendorid) as NbrVendors

FROM country c, region r, province p, vendor v

WHERE c.countryid = r.countryid and

r.regionid = p.regionid and

p.provinceid = v.provinceid

GROUP BY ____________ORDER BY 1,2 desc;

What goes in the GROUP BY clause?

Page 7

?

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Group ByProblem: How many vendors are in each country? Show by Country and Region.

SELECT c.countryname, r.regionname,

count(vendorid) as NbrVendors

FROM country c, region r, province p, vendor v

WHERE c.countryid = r.countryid and

r.regionid = p.regionid and

p.provinceid = v.provinceid

GROUP BY c.countryname, r.regionname

ORDER BY 1,2 desc;

Page 8

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Group ByProblem: What is the average, min and max hourly rate by user location?

SELECT userLocation,

avg(hourlyRate) as Avg_Hourly_Rate,

min(hourlyRate) as Min_Hourly_Rate,

max(hourlyRate) as Max_Hourly_Rate

FROM User

GROUP BY userLocation

ORDER BY avg(hourlyRate);

USERLOCATION AVG_HOURLY_RATE MIN_HOURLY_RATE MAX_HOURLY_RATE

Boston 62.03 49.99 76.44

San Francisco 64.6175 57.45 71.01

Bangkok 76.405 63.45 89.51

Page 9

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Group By and Having

Problem: Retrieve all products containing less than 40 components.

SELECT Product.PRODUCTID, Sum(RequiredQTY) AS

NumComponents

FROM Product, Manifest

WHERE Product.ProductID = Manifest.ProductID

GROUP BY Product.PRODUCTID

HAVING Sum(RequiredQTY) < 40;

WHERE Filters out Rows that don’t satisfy the search conditions.

HAVING Filters out Groups that don’t satisfy the search conditions.

PRODUCTID

NUMCOMPONENTS

4 39

12 39

17 38

31 39

49 37

61 36

•6 rows selected.

Page 10

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Group By and Having

Problem: Which customers have more than 9 users?

SELECT ct.customerTypeDescription as CustomerType,

c.customerName as Customer,

count(*) as NbrUsers

FROM CustomerType ct, Customer c, Users u

WHERE ct.customertypeid = c.customertypeid and

c.customerid = u.customerid

GROUP BY ______________________

HAVING ______________________

ORDER BY 1,3 desc;

12 Rows

CUSTOMERTYPE CUSTOMER NBRUSERS

Consumer The Coca-Cola Company 31

Consumer Kellogg Co. 28

Consumer Kraft Foods Inc. 20

Consumer Proctor & Gamble Company 20

Consumer Unilever plc 15

Media GMR Marketing 15

Media VML 12

Media Proximity Worldwide 12

Media Resolution Media 11

Media LatinWorks 11

Media Burson-Marsteller 10

Media Chime Communications 10

Page 11

Useful Functions

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Arithmetic ExpressionsProblem: Multiply the vendor price by 1.05 where ComponentID < 10 and VendorID = 1

VENDORID COMPONENTID VENDORPRICE NEWPRICE

1 1 187.67 197.0535

1 2 206.03 216.3315

1 3 178.63 187.5615

1 4 187.65 197.0325

1 5 199.72 209.706

1 6 154.73 162.4665

1 7 196.21 206.0205

1 8 181.99 191.0895

1 9 182.47 191.5935 9 rows selected.

SELECT VendorID, ComponentID, VendorPrice, VendorPrice * 1.05 as NewPrice

From VendorComponentWhere VendorID =1 and ComponentID < 10;

Page 13

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Select – Scalar Functions• A scalar row function returns a single result row for every row of a

queried table or view.

• Single row functions can appear in select lists (provided the SELECT statement does not contain a GROUP BY clause) and WHERE clauses.

• Number Functions: Number functions accept numeric input and return numeric values.

ROUND Syntax ROUND(n[,m])

Returns n rounded to m places right of the decimal point. If m is omitted, to 0 places. m can be negative to round off digits left of the decimal point. m must be an integer.

SELECT ComponentID, Avg(VendorPrice) As Avg,ROUND(Avg(VendorPrice)) As Round

FROM VendorComponentGroup By ComponentIDOrder By ComponentID;

COMPONENTID AVG ROUND

1 187.6

7

188

2 206.0

3

206

3 178.6

3

179

4 187.6

5

188

5 199.7

2

200

898 rows selected . Note: not all rows are displayed in this report due to size constraints of this page.

Page 14

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Some Useful Scalar Functions

ABS Syntax ABS(n) Returns the absolute value of n

CEIL Syntax CEIL(n) Returns smallest integer greater than or equal to n.

FLOOR Syntax FLOOR(n) Returns largest integer equal to or less than n.

ROUND Syntax ROUND(n[,m]) Returns n rounded to m places right of the decimal point.

TRUNC Syntax TRUNC(n[,m]) Returns n truncated to m decimal places.

Page 15

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Some Useful Character Functions

SUBSTR Syntax SUBSTR(char, m [,n])

Returns a portion of char, beginning at character m, n characters long. If m is 0, it is treated as 1. If m is positive, Oracle counts from the beginning of char to find the first character. If m is negative, Oracle counts backwards from the end of char. If n is omitted, Oracle returns all characters to the end of char. If n is less than 1, a null is returned.

Select substr(VendorFirstName,1,1) || ', ' || VendorLastName

from Vendor;

UPPER Syntax UPPER(char) Returns char, with all letters uppercase.

Select * from Vendor where Upper(City) = ‘BOSTON’;

Page 16

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Some Useful Character FunctionsLENGTH Syntax LENGTH(char) Returns the length of char in characters. If char has datatype CHAR, the length includes all trailing blanks. If char is null, this function returns null.

LOWER Syntax LOWER(char) Returns char, with all letters lowercase. The return value has the same datatype as the argument char (CHAR or VARCHAR2).

LTRIM Syntax LTRIM(char [,set] Removes characters from the left of char, with all the leftmost characters that appear in set removed. Set defaults to a single blank. Oracle begins scanning char from its first character and removes all characters that appear in set until reaching a character not in set and then returns the result.

REPLACE Syntax REPLACE(char, search_string[,replacement_string])

Returns char with every occurrence of search_string replaced with replacement_string. If

replacement_string is omitted or null, all occurrences of search_string are removed. If search_string is null, char is returned. Page 17

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

TO_CHAR FunctionThe TO_CHAR function converts a number or date to a string. The syntax for the

to_char function is: to_char(value,[format_mask]). The value field can be either a

number or a date.

Example – Numbers:to_char(1210.73,’9999.9’) would return ‘1210.7’

to_char(1210.73,’9999.99’) would return ‘1210.73’

to_char(1210.73,’$9,999.99’) would return ‘$1,210.73’

Example – Dates:to_char(actualEndDate,’mm/dd/yyyy’) would return ‘05/17/2009’

to_char(actualEndDate,’Month DD, YYYY’) would return ‘May 17, 2009’

to_char(actualEndDate,’YYYY’) would return ‘2009’

to_char(actualEndDate,’MM’) would return ‘05’

to_char(actualEndDate,’DD’) would return ‘17’

to_char(actualEndDate,’D’) would return ‘1’ or Sunday

to_char(actualEndDate,’SSSSS’) would return ‘30370’

Page 18

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Date Conversion ExamplesSELECT factoryid,

to_char(actualEndDate,'mm/dd/yyyy') as ShortDate,to_char(actualEndDate,'Month DD, YYYY') as LongDate,to_char(actualEndDate,'YYYY') as Year,to_char(actualEndDate,'MM') as Month,to_char(actualEndDate,'DD') as Day,to_char(actualEndDate,'D') as DayOfWeek,to_char(actualEndDate,'SSSSS') as SecondsAfterMidnight,cast(actualEndDate as TimeStamp) as Timestamp

FROM factory WHERE to_char(actualEndDate,'MM') = 5 and to_char(actualEndDate,'DD') = 17 and

to_char(actualEndDate,'YYYY') = 2009;

FACTORYID SHORTDATE LONGDATE YEAR MONTH DAY DAYOFWEEK SECONDSAFTERMIDNIGHT TIMESTAMP

267065 5/17/2009 17-May-09 2009 5 17 1 27318 17-MAY-09 07.35.18.000000 AM

267066 5/17/2009 17-May-09 2009 5 17 1 27338 17-MAY-09 07.35.38.000000 AM

267067 5/17/2009 17-May-09 2009 5 17 1 27359 17-MAY-09 07.35.59.000000 AM

267068 5/17/2009 17-May-09 2009 5 17 1 27380 17-MAY-09 07.36.20.000000 AM

267069 5/17/2009 17-May-09 2009 5 17 1 27400 17-MAY-09 07.36.40.000000 AM

Page 19

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Date Conversion ParametersParameter Explanation Parameter Explanation

YEAR Year, spelled out WWeek of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.

YYYY 4-digit year IWWeek of year (1-52 or 1-53) based on the ISO standard.

YYY

Last 3, 2, or 1 digit(s) of year.

D Day of week (1-7).

YY DAY Name of day.

Y DD Day of month (1-31).

IYY

Last 3, 2, or 1 digit(s) of ISO year.

DDD Day of year (1-366).

IY DY Abbreviated name of day.

I JJulian day; the number of days since January 1, 4712 BC.

IYYY 4-digit year based on the ISO standard HH Hour of day (1-12).

Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1). HH12 Hour of day (1-12).

MM Month (01-12; JAN = 01). HH24 Hour of day (0-23).

MON Abbreviated name of month. MI Minute (0-59).

MONTHName of month, padded with blanks to length of 9 characters.

SS Second (0-59).

RM Roman numeral month (I-XII; JAN = I). SSSSS Seconds past midnight (0-86399).

WWWeek of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.

FF Fractional seconds.

ISO date example, 2006-W52-7 (or in compact form 2006W527) is the Sunday of the 52nd week of 2006.

Page 20

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Working with Dates

SELECT incidentId, openDate

FROM Incident

WHERE OpenDate Between '11/1/2008' and '11/5/2008';

Problem: What incidents were opened Nov 1 and Nov 5, 2008?

Page 21

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Working with Dates

SELECT incidentID, openDate

FROM Incident

WHERE openDate Between '1-Nov-2008' and '5-Nov-2008';

Problem: What incidents were opened between Nov 1 and Nov 5, 2008?

But what if the dates aren’t in this format?

53 Rows

INCIDENTID OPENDATE50 2-Nov-0890 3-Nov-08

178 4-Nov-08258 3-Nov-08

1027 3-Nov-081219 1-Nov-081277 1-Nov-081372 2-Nov-081442 1-Nov-08

...

Page 22

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Working with Dates

SELECT incidentID, openDate

FROM Incident

WHERE openDate Between to_date('11/1/2008', 'MM/DD/YYYY')

and to_date('11/5/2008','MM/DD/YYYY');

Problem: What incidents were opened between Nov 1 and Nov 5, 2008?

53 Rows

INCIDENTID OPENDATE50 2-Nov-0890 3-Nov-08

178 4-Nov-08258 3-Nov-08

1027 3-Nov-081219 1-Nov-081277 1-Nov-081372 2-Nov-081442 1-Nov-08

...

In Oracle, the to_date function converts a string

to a date

Page 23

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Date ArithmeticProblem: How many minutes did Nielsen engineers work on incidents 1-10?

SELECT i.incidentID, round(sum(ia.checkout - ia.checkin) * 1440) as actualTimeMinutesFROM IncidentAction ia, Incident iWHERE i.incidentID = ia.incidentID and i.incidentID between 1 and 10GROUP BY i.incidentID;

INCIDENTID ACTUALTIMEMINUTES1 4306 4182 4194 4455 3918 4623 3677 3619 382

10 319

Note: Date1 – Date2 = DaysDiff

Page 24

Workshop

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Individual SQL Workshop 2 – Starter DB

Page 26

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

8 rows selected.

Problem 1 – Aggregate Functions

Problem: List all the Regions in the United States (CountryID = 1). Count the number of Provinces in each Region. Order by RegionName.

COUNTRYNAME REGIONNAME NBRPROVINCES

United States Alaska 2

United States Midatlantic 8

United States Midwest 12

United States Mountain 4

United States Northeast 8

United States Northwest 2

United States Southeast 8

United States Southwest 6

Page 27

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.•12 rows selected.

Problem 2 – Aggregate Functions

Problem: For all Products whose ProductID less than or equal to 12, calculate the Cost of the Components, and their Margin Amount (Product Price – Component Cost). Order the Report by MarginAmt in descending

sequence.Note: In the Manifest Table is a field named RequiredQty. This field contains the number of components required to build the homegen. For example, if the component was a wheel, then RequiredQty for the wheel component would equal 4. Also in the VendorComponent table is the field VendorCost. VendorCost contains price we pay the Vendor for each component.

PRODUCTID PRODUCTDESCRIPTION FUELSOURCEDESCRIPTION PRODUCTPRICE COMPONENTCOST MARGINAMT

4 HomeGen 3000 - LP Gas, 110v 50Hz LP Gas 8059 3996.95 4062.05

2 HomeGen 3000 - Natural Gas, 220v 50Hz

Natural Gas 9966 6262.09 3703.91

9 HomeGen 3000 - Propane, 240v 60Hz Propane 8799 5424.45 3374.55

12 HomeGen 3000 - Butane, 240v 60Hz Butane 7653 4368.13 3284.87

7 HomeGen 3000 - Propane, 110v 50Hz Propane 7532 4517.86 3014.14

6 HomeGen 3000 - LP Gas, 240v 60Hz LP Gas 9252 6909.9 2342.1

1 HomeGen 3000 - Natural Gas, 110v 50Hz

Natural Gas 6961 5453.58 1507.42

10 HomeGen 3000 - Butane, 110v 50Hz Butane 8716 7222.93 1493.07

3 HomeGen 3000 - Natural Gas, 240v 60Hz

Natural Gas 5975 4784.28 1190.72

8 HomeGen 3000 - Propane, 220v 50Hz Propane 6680 5576.96 1103.04

5 HomeGen 3000 - LP Gas, 220v 50Hz LP Gas 5575 5161.83 413.17

11 HomeGen 3000 - Butane, 220v 50Hz Butane 5388 5047.71 340.29

Page 28

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Problem 3 – Select SUBSTR and Concatenation

Problem: Select all vendors in the Vendor table where the city starts with the character ‘B’. In the report, concatenate the first character of the first name of the vendor with their last name. Order the report in ascending sequence on the VendorID column.

5 rows selected.

VENDORID

NAME CITY PROVINCEABBREVIATION COUNTRYNAME CURRENCYNAME

3 W, Martin

Belpre OH United States US Dollar

8 R, Rascoe

Brooklyn NY United States US Dollar

9 R, Benoit Bronxville NY United States US Dollar

12 F, Barbuto

Boston MA United States US Dollar

20 A, Pfeiffer

Birmingham

AL United States US Dollar

Page 29

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Problem 4 – Select using GROUP BY and Column Functions

Problem: Group all PowerRating(s) represented in the Product column.

• Include a Count of the number of rows in each grouping.

• Calculate the Average, Maximum, Minimum ProductPrice column.

• Include Order the report in ascending sequence by PowerRating.

Note: To arrive at the “proper” AVGPRICE, you will have to round your

average.

7 rows selected.

POWERRATING COUNT AVGPRICE MINPRICE MAXPRICE

3000 12 7546.33 5388 9966

4000 12 7827.08 5130 9645

5000 12 8435.5 5757 9955

6000 12 7867 5309 10103

7000 12 7845.33 5488 9463

8000 12 8237.25 5867 9678

9000 12 8492.42 6449 9878

Page 30

•Confidential & ProprietaryCopyright © 2009 Cardinal Directions, Inc.

Problem 5 – Select using GROUP BY and HAVING

Problem: Group all PowerRating(s) represented in the Product table. Then display a Count of the rows in the group, and calculate the Average, Maximum and Minimum ProductPrice column.

• Only include in the report products that have a ProductDescription that contains the characters 'Butane'.

• Only include in the report those groups that have greater than or equal to 3 rows

• Only include in the report those groups that have an Average ProductPrice amount greater than or equal to 7000 dollars.

• Order the report in ascending sequence by PowerRating.

Note: To arrive at the “proper” AVGPRICE, you will have to round your average.

6 rows selected.

POWERRATING COUNT AVGPRICE MINPRICE MAXPRICE

3000 3 7252.33 5388 8716

4000 3 8209 6576 9638

5000 3 8359 6067 9955

6000 3 7974.67 7525 8447

8000 3 9011.67 7831 9602

9000 3 8410 6716 9878

Page 31