Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Training ORACLE SQL Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Write SQL Statements using:

Similar presentations


Presentation on theme: "SQL Training ORACLE SQL Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Write SQL Statements using:"— Presentation transcript:

1 SQL Training ORACLE SQL Functions

2 Confidential & Proprietary Copyright © 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:

3 Aggregate Functions

4 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Select – Aggregate Functions The following aggregate functions can be applied to multiple values retrieved from a table. FunctionPurpose MINYields the minimum value in a column MAXYields the maximum value in a column AVGComputes the average value for a column SUMComputes the total value for a column COUNTLists the number of rows in a query, or lists the number of distinct column values Page 4

5 Group By and Having

6 Confidential & Proprietary Copyright © 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 NumComponents From Product, Manifest Where Product.ProductID = Manifest.ProductID and Product.ProductID = 15 Group By Product.ProductID, Product.ProductDescription; PRODUCTIDPRODUCTDESCRIPTIONNUMCOMPONENTS 15HomeGen 4000 - Natural Gas, 240v 60Hz43 All fields in the SELECT clause that are not part of an aggregate function must be included in the GROUP BY clause.

7 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By Problem: 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 ?

8 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By Problem: 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

9 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By Problem: 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); USERLOCATIONAVG_HOURLY_RATEMIN_HOURLY_RATEMAX_HOURLY_RATE Boston62.0349.9976.44 San Francisco64.617557.4571.01 Bangkok76.40563.4589.51 Page 9

10 Confidential & Proprietary Copyright © 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. PRODUCT ID NUMCOMPONE NTS 439 1239 1738 3139 4937 6136 6 rows selected. Page 10

11 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Group By and Having Problem: Which customers have more than 9 users? SELECTct.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 CUSTOMERTYPECUSTOMERNBRUSERS ConsumerThe Coca-Cola Company31 ConsumerKellogg Co.28 ConsumerKraft Foods Inc.20 ConsumerProctor & Gamble Company20 ConsumerUnilever plc15 MediaGMR Marketing15 MediaVML12 MediaProximity Worldwide12 MediaResolution Media11 MediaLatinWorks11 MediaBurson-Marsteller10 MediaChime Communications10 Page 11

12 Useful Functions

13 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Arithmetic Expressions Problem: Multiply the vendor price by 1.05 where ComponentID < 10 and VendorID = 1 VENDORIDCOMPONENTIDVENDORPRICENEWPRICE 11187.67197.0535 12206.03216.3315 13178.63187.5615 14187.65197.0325 15199.72209.706 16154.73162.4665 17196.21206.0205 18181.99191.0895 19182.47191.5935 9 rows selected. SELECT VendorID, ComponentID, VendorPrice, VendorPrice * 1.05 as NewPrice From VendorComponent Where VendorID =1 and ComponentID < 10; Page 13

14 Confidential & Proprietary Copyright © 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 VendorComponent Group By ComponentID Order By ComponentID; COMPONENTIDAVGROUND 1187.67188 2206.03206 3178.63179 4187.65188 5199.72200 898 rows selected. Note: not all rows are displayed in this report due to size constraints of this page. Page 14

15 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Some Useful Scalar Functions ABSSyntax ABS(n) Returns the absolute value of n CEILSyntax CEIL(n) Returns smallest integer greater than or equal to n. FLOORSyntax FLOOR(n) Returns largest integer equal to or less than n. ROUNDSyntax ROUND(n[,m]) Returns n rounded to m places right of the decimal point. TRUNCSyntax TRUNC(n[,m])Returns n truncated to m decimal places. Page 15

16 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Some Useful Character Functions SUBSTRSyntax 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; UPPERSyntax UPPER(char)Returns char, with all letters uppercase. Select * from Vendor where Upper(City) = ‘BOSTON’; Page 16

17 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Some Useful Character Functions LENGTHSyntax 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. LOWERSyntax 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

18 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. TO_CHAR Function The 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

19 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Date Conversion Examples SELECT 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; FACTORYIDSHORTDATELONGDATEYEARMONTHDAYDAYOFWEEKSECONDSAFTERMIDNIGHTTIMESTAMP 2670655/17/200917-May-09200951712731817-MAY-09 07.35.18.000000 AM 2670665/17/200917-May-09200951712733817-MAY-09 07.35.38.000000 AM 2670675/17/200917-May-09200951712735917-MAY-09 07.35.59.000000 AM 2670685/17/200917-May-09200951712738017-MAY-09 07.36.20.000000 AM 2670695/17/200917-May-09200951712740017-MAY-09 07.36.40.000000 AM Page 19

20 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Date Conversion Parameters ParameterExplanationParameterExplanation YEARYear, spelled outW Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh. YYYY4-digit yearIW Week of year (1-52 or 1-53) based on the ISO standard. YYY Last 3, 2, or 1 digit(s) of year. DDay of week (1-7). YYDAYName of day. YDDDay of month (1-31). IYY Last 3, 2, or 1 digit(s) of ISO year. DDDDay of year (1-366). IYDYAbbreviated name of day. IJ Julian day; the number of days since January 1, 4712 BC. IYYY4-digit year based on the ISO standardHHHour of day (1-12). QQuarter of year (1, 2, 3, 4; JAN-MAR = 1).HH12Hour of day (1-12). MMMonth (01-12; JAN = 01).HH24Hour of day (0-23). MONAbbreviated name of month.MIMinute (0-59). MONTH Name of month, padded with blanks to length of 9 characters. SSSecond (0-59). RMRoman numeral month (I-XII; JAN = I).SSSSSSeconds past midnight (0-86399). WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year. FFFractional seconds. ISO date example, 2006-W52-7 (or in compact form 2006W527) is the Sunday of the 52nd week of 2006. Page 20

21 Confidential & Proprietary Copyright © 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

22 Confidential & Proprietary Copyright © 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 INCIDENTIDOPENDATE 502-Nov-08 903-Nov-08 1784-Nov-08 2583-Nov-08 10273-Nov-08 12191-Nov-08 12771-Nov-08 13722-Nov-08 14421-Nov-08... Page 22

23 Confidential & Proprietary Copyright © 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 INCIDENTIDOPENDATE 502-Nov-08 903-Nov-08 1784-Nov-08 2583-Nov-08 10273-Nov-08 12191-Nov-08 12771-Nov-08 13722-Nov-08 14421-Nov-08... In Oracle, the to_date function converts a string to a date Page 23

24 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Date Arithmetic Problem: How many minutes did Nielsen engineers work on incidents 1-10? SELECT i.incidentID, round(sum(ia.checkout - ia.checkin) * 1440) as actualTimeMinutes FROM IncidentAction ia, Incident i WHERE i.incidentID = ia.incidentID and i.incidentID between 1 and 10 GROUP BY i.incidentID; INCIDENTIDACTUALTIMEMINUTES 1430 6418 2419 4445 5391 8462 3367 7361 9382 10319 Note: Date1 – Date2 = DaysDiff Page 24

25 Workshop

26 Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Individual SQL Workshop 2 – Starter DB Page 26

27 Confidential & Proprietary Copyright © 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. COUNTRYNAMEREGIONNAMENBRPROVINCES United StatesAlaska2 United StatesMidatlantic8 United StatesMidwest12 United StatesMountain4 United StatesNortheast8 United StatesNorthwest2 United StatesSoutheast8 United StatesSouthwest6 Page 27

28 Confidential & Proprietary Copyright © 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. PRODUCTIDPRODUCTDESCRIPTIONFUELSOURCEDESCRIPTIONPRODUCTPRICECOMPONENTCOSTMARGINAMT 4HomeGen 3000 - LP Gas, 110v 50HzLP Gas80593996.954062.05 2HomeGen 3000 - Natural Gas, 220v 50HzNatural Gas99666262.093703.91 9HomeGen 3000 - Propane, 240v 60HzPropane87995424.453374.55 12HomeGen 3000 - Butane, 240v 60HzButane76534368.133284.87 7HomeGen 3000 - Propane, 110v 50HzPropane75324517.863014.14 6HomeGen 3000 - LP Gas, 240v 60HzLP Gas92526909.92342.1 1HomeGen 3000 - Natural Gas, 110v 50HzNatural Gas69615453.581507.42 10HomeGen 3000 - Butane, 110v 50HzButane87167222.931493.07 3HomeGen 3000 - Natural Gas, 240v 60HzNatural Gas59754784.281190.72 8HomeGen 3000 - Propane, 220v 50HzPropane66805576.961103.04 5HomeGen 3000 - LP Gas, 220v 50HzLP Gas55755161.83413.17 11HomeGen 3000 - Butane, 220v 50HzButane53885047.71340.29 Page 28

29 Confidential & Proprietary Copyright © 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. VENDORIDNAMECITYPROVINCEABBREVIATIONCOUNTRYNAMECURRENCYNAME 3W, MartinBelpreOHUnited StatesUS Dollar 8R, RascoeBrooklynNYUnited StatesUS Dollar 9R, BenoitBronxvilleNYUnited StatesUS Dollar 12F, BarbutoBostonMAUnited StatesUS Dollar 20A, PfeifferBirminghamALUnited StatesUS Dollar Page 29

30 Confidential & Proprietary Copyright © 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. POWERRATINGCOUNTAVGPRICEMINPRICEMAXPRICE 3000127546.3353889966 4000127827.0851309645 5000128435.557579955 6000127867530910103 7000127845.3354889463 8000128237.2558679678 9000128492.4264499878 Page 30

31 Confidential & Proprietary Copyright © 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. POWERRATINGCOUNTAVGPRICEMINPRICEMAXPRICE 300037252.3353888716 40003820965769638 50003835960679955 600037974.6775258447 800039011.6778319602 90003841067169878 Page 31


Download ppt "SQL Training ORACLE SQL Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. Lesson Objectives Write SQL Statements using:"

Similar presentations


Ads by Google