Purpose of chapter is to show how ... - Welcome | ICT Seneca



Les02 Using Single Row FunctionsPurpose of chapter is to show how to further Customize outputCompanies need lots of different answers to use in decision makingObjectivesAfter completing this lesson, you should be able to do the following:- Describe various types of functions that are available in SQL- Use 1character, 2number, and 3date functions in SELECT Statements- Describe the use of conversion functionsObjectivesFunctionsà make the basic query block more powerful,and à they are used to manipulate data values. This is the first of two lessons that explore functions. Focus is onSingle-row character, number, and date functionsFunctions that convert data from one type to another -- For example, conversion from character data to numeric dataSQL Functions 3-3SQL functionsFunctions are very powerful feature of SQL. They can be used to do the following:Perform calculations on dataModify individual data itemsManipulate output for groups of rowsFormat dates and numbers for displayConvert column data typesSQL functions sometimes take arguments and always return a valueNote: Most of the functions that are described in this lesson are specific to a version of SQL3-4SQL functions2 Types of Functions:Single-Row functionsMultiple-row functionsSingle-Row functionsThese functions operate on single rows only and return one result for every row acted on.There are different types of Single-Row functions as follows:CharacterNumberDateConversionGeneralMultiple-row functionsFunctions can manipulate groups of rows to give one result per group of rows.These functions are also called group functions.Note: we will only cover some of these on the course for all others refer to the oracle SQL reference guide.3-5Single-Row functionsThese functions manipulate data items.Expect one or more arguments and return a single value for each row that is retrieved by the query.An argument can be one of the following:User supplied constantVariable valueColumn nameExpressionThe actions of single row functions include:Acts on each row that is returned by the queryReturns one result per rowMay possibly return a different data type than the one that is referencedThe function expects one or more argumentsCan be used in THESelectWhereOrder by- can also be nested3-6Only the following are covered in this chapter3-7Function accepts character data àà returns character and numeric data2 groupsà Case ManipulationEXAMPLES on next slidesà Character ManipulationLOWER (Column or Expression) UPPERINITCAP – changes string to Initial letter in each word is capitalizedSUBSTR – needs string or column and starting position and lengthCONCAT – like || -- needs 2 argumentsLENGTH – returns number of characters in the expressionSELECTLENGTH (CONCAT (first_name, last_name)) from employeesINSTR – returns the numeric position of a named string-- you can give it a starting position before countingLPAD – pads the character value right justifiedRPAD – pads the character value shown by the amount not filled by the filedselect RPAD ( first_name, 9 , '*' ) from employeesTRIMREPLACEExamples on next set of slidesEllen**** Curtis*** 3-9SELECT LOWER (first_name) FROM employeesNOTE: The column headings are not business-like and need fixing3-10USING CASE MANIPUTLATION FUNCTIONSDisplay the employee number, the first name, the last name, and Job Title for and employee called higginsNote that the user will enter higgins all in lower caseSELECT employee_id, first_name, Last_name, job_titleFROM employeesWHERE last_name = 'higgins';Because Higgins is all in lower case it does not find a match in the tableWHAT IS THE RESULT?Let us improve it to get a resultConvert the data stored in the database to LOWER case and match it to the inputselect employee_id, last_name, department_idfrom employeesAlthough you are hard coding for now, in reality it is on a form and the user enters the name.where lower(last_name) = 'higgins'This assumes the user will enter it as lower caseMake user enter the dataselect employee_id, last_name, department_idfrom employeeswhere lower(last_name) = lower(‘&Last_Name’) Case statement on BOTH sides covers all possibilities.Make it simpler for the user3-11Demonstrate REPLACE:SELECT REPLACE (last_name, 'Ab', 'AAAA')FROM employeesNote: You can use functions such as UPPER and LOWER with ampersand substitution. For example, use UPPER ('&job_title') so that the user does not have to enter the job title in a specific case.3-12Using Character ManipulationPROBLEM: Display the first name and last name joined. Call that column NAMEDisplay job_titleLength of last_nameWhat position in last name is the letter 'a'But only show those whose where job_title begins with a co in position 3 and 4===========================================================Just a copy of a previous page to help you answer the aboveSELECT employee_id, CONCAT (first_name, last_name) NAME, job_title, LENGTH (last_name), INSTR (last_name, 'a') "contains an 'a'"FROM employeesWHERE SUBSTR (job_title, 3,1) = 'c';OUTPUTEMPLOYEE_ID NAME JOB_TITLE LENGTH(LAST_NAME) contains an 'a'----------- ------------------------------ ----------------------------------- ----------------- --------------- 106 RoseStephens Accounting Manager 8 0 11 TylerRamirez Accountant 7 2 10 RyanGray Accountant 4 3 14 ElliotBrooks Accountant 6 0 12 ElliottJames Accountant 5 2 13 AlbertWatson Accountant 6 26 rows selected.The above example displays employee 1 first names and last names joined.2 the length of the employee last name, and 3 the numeric position of the letter a in the string, employee last name And for all employees That have the string “co” contained in the job title. Starting at the 3rd position of the job title.PROBLEM:Modify the previous SQL statement to display the data for those employees whose last names end with the letter a.SELECT employee_id, CONCAT (first_name, last_name) NAME, job_title, LENGTH (last_name) as Length, INSTR (last_name, 'a') as "has A"FROM employeesWHERE SUBSTR(last_name, -1, 1) = 'a'; EMPLOYEE_ID NAME JOB_TITLE LENGTH has A----------- ------------------------------ ----------------------------------- ---------- ---------- 2 JudeRivera Administration Vice President 6 6WHERE SUBSTR(last_name, -1, 1) = 'a' ; ? this gets those with last _name ending in aThe -1 means start at 1 less than the end and process 1 value (which is now the end) -- And is that value equal to n3-13This is a straightforward example Try thisSELECT salary, -- the original salary in tableround (salary, -3)-- the same salary roundedFROM employees Salary rounded to thousandssalary 3-14 Again, this is simple functionsNOTE:DUAL used because SELECT and FROM are mandatory… but the data does not come from any columns or tablesIf use 0 or no value it is rounded to zero decimal placesSELECT salary * 1.3 +23.456, round (salary *1.3+23.456) -- rounding to whole dollarsFROM employees13673.456 13673 14323.456 14323 11203.456 11203 9123.456 9123 3-15Works the same as ROUND3-16 Gives the remainder .. AFTER the amount is subtracted as many times as possible…. Like C programmingUsed often to determine if a value is odd or even3-17 DATESNOTE:Default date display format. Company may choose different defaults for display. Actual date stored differently. Full date and timeJune 17, 1987, 5:10:43 p.mRR – goes back to pre-2000 times to avoid a problemThe Oracle database stores dates in an internal numeric format, representing the century, year, month, day, hours, minutes, and seconds.The default display and input format for any date is DD-MON-RR. Valid Oracle dates are between January 1, 4712 B.C., and December 31, 9999 A.D.In the example in the slide, the HIRE_DATE column output is displayed in the default format DD-MON-RR. However, dates are not stored in the database in this format. All the components of the date and time are stored. So, although a HIRE_DATE such as 17-JUN-87 is displayed as day, month, and year, there is also time and century information associated with the date. The complete data might be June 17, 1987, 5:10:43 p.m.CENTURY YEAR MONTH DAY HOUR MINUTE SECOND19 87 06 17 17 10 43Note: century or year stored as 4 digits even if displayed as 23-19TEST IT --- this will well you the format to useSELECT SYSDATEFROM DUALWas the formatSYSDATE ---------17-SEP-18 CurrentlySYSDATE --------20-05-213-20MAJOR IMPORTANCE TO BUSINESSBUSINESS RUNS ON DATES AND DOLLARSSample hoursSELECT last_name, hire_date, hire_date + 36/24FROM employeesLAST_NAME HIRE_DAT HIRE_DAT--------------- -------- --------Long 16-09-28 16-09-29Patterson 16-01-14 16-01-15Hughes 16-03-08 16-03-09Flores 16-08-20 16-08-21Washington 16-10-30 16-10-31When a business sells goods or products to another it usually isn’t for immediate payment. The seller offers terms.Sample: NET 302%NET10On the invoice is the date the invoice is made or billed, and the date 30 days later for when the payment is due.3-21Using Arithmetic Operators with DatesPROBLEM:Find how many weeks an employee has worked at the company and only for department 90Answer looking for is:LAST_NAME Weeks Employed------------------------- --------------King 1526.509089 Kochhar 1408.366232 De Haan 1235.509089SELECT last_name, (sysdate - hire_date)/7 "Weeks Employed" -- returns days converted to weeksFROM employeesLAST_NAME Weeks Employed--------------- --------------Russell 201.068621Griffin 186.211478Diaz 222.925764Perry 183.211478Jenkins 188.497192Coleman 211.64005Henderson 214.64005Ross 200.497192107 rows selected.This answer is not very good …. Improve itSELECT last_name, trunc((sysdate - hire_date)/7, 2) "Weeks Employed"FROM employeesWhy does it end in .5 ? and not 2 decimal placesLAST_NAME Weeks Employed------------------------- --------------King 1526.5 Kochhar 1408.36 3-22EX: next page3-23EXAMPLE:SELECTNEXT_DAY ('20-05-22','TUESDAY') AS "Next Tuesday"FROM dual;Next Tue--------20-05-26PROBLEM: Try thisDisplay the employee number, hire date, - number of months employed, - six-month from now is the employees review date, - what is the first Friday after hire date, and- last day of the hire month for all employees who have been employed for fewer than 70 months.ANS: Next pageSELECT employee_id, hire_date, MONTHS_BETWEEN (SYSDATE, hire_date) "Seniority", ADD_MONTHS (hire_date, 6) "Review Date", NEXT_DAY (hire_date, 'Friday'), LAST_DAY (hire_date)FROM employeesWHERE MONTHS_BETWEEN (SYSDATE, hire_date) > 70;EMPLOYEE_ID HIRE_DATE Seniority Review Date NEXT_DAY(HIRE_DATE,'FRIDAY') LAST_DAY(HIRE_DATE)----------- --------- ---------- ----------- ---------------------------- ------------------- 100 17-JUN-87 359.0790647 17-DEC-87 19-JUN-87 30-JUN-87 101 21-SEP-89 331.9500325 21-MAR-90 22-SEP-89 30-SEP-89 102 13-JAN-93 292.208097 13-JUL-93 15-JAN-93 31-JAN-93 103 03-JAN-90 328.5306776 03-JUL-90 05-JAN-90 31-JAN-90 104 21-MAY-91 311.9500325 21-NOV-91 24-MAY-91 31-MAY-91 107 07-FEB-99 219.4016454 07-AUG-99 12-FEB-99 28-FEB-99 124 16-NOV-99 210.1113228 16-MAY-00 19-NOV-99 30-NOV-99 141 17-OCT-95 259.0790647 17-APR-96 20-OCT-95 31-OCT-95 142 29-JAN-97 243.691968 29-JUL-97 31-JAN-97 31-JAN-97 143 15-MAR-98 230.1435809 15-SEP-98 20-MAR-98 31-MAR-98 144 09-JUL-98 226.3371293 09-JAN-99 10-JUL-98 31-JUL-98 149 29-JAN-00 207.691968 29-JUL-00 04-FEB-00 31-JAN-00 174 11-MAY-96 252.2726131 11-NOV-96 17-MAY-96 31-MAY-96 176 24-MAR-98 229.8532583 24-SEP-98 27-MAR-98 31-MAR-98 178 24-MAY-99 215.8532583 24-NOV-99 28-MAY-99 31-MAY-99 200 17-SEP-87 356.0790647 17-MAR-88 18-SEP-87 30-SEP-87 201 17-FEB-96 255.0790647 17-AUG-96 23-FEB-96 29-FEB-96 202 17-AUG-97 237.0790647 17-FEB-98 22-AUG-97 31-AUG-97 205 07-JUN-94 275.4016454 07-DEC-94 10-JUN-94 30-JUN-94 206 07-JUN-94 275.4016454 07-DEC-94 10-JUN-94 30-JUN-94 207 01-JUL-00 202.5951938 01-JAN-01 07-JUL-00 31-JUL-00 21 rows selected --- currently 23 rows 3-24Using Date FunctionsTry these to see result based on current sysdateThe ROUND and TRUNC functions can be used for number and date values.When used with dates, these functions round or truncate to the specified format model. Therefore, you can round dates to the nearest year or month.ORIGINAL DATE is in SEPTEMBER 2018ROUND __ MONTHselect round(sysdate, 'month')from dual;ROUND(SYSDATE,'MONTH')----------------------01-OCT-18 TRUNC ___ Month TRUNC(SYSDATE,'MONTH')----------------------01-SEP-18 select round(sysdate, 'year')from dual; ROUND(SYSDATE,'YEAR')---------------------01-JAN-19 TRUNC(SYSDATE,'YEAR')---------------------01-JAN-18 PROBLEM:Compare the hire dates for all employees who started in 1997. Display the employee number, hire date, and start month using the ROUND and TRUNC functions.SELECT employee_id, hire_date,ROUND(hire_date, 'MONTH') as Started_Month_Rounded, TRUNC(hire_date, 'MONTH') as TruncatedFROM employeesWHERE hire_date LIKE '%97'; OracleExpress in Jan 2015 has a different default date style, but result is the same dataEMPLOYEE_IDHIRE_DATESTARTED_MONTH_ROUNDEDTRUNCATED14201/29/199702/01/199701/01/199720208/17/199709/01/199708/01/1997USING EMPLOYEES in 2020-1 dataSELECT employee_id, hire_date,ROUND(hire_date, 'MONTH') as Started_Month_Rounded, TRUNC(hire_date, 'MONTH') as TruncatedFROM employeesWHERE hire_date LIKE '16%'; EXERCISE for you to do at back of Oracle book chapter3-26Conversion Functions2 Types-Implicit-Explicit3-27IMPLICIT- what the Oracle software does itself.EXPLICIT- what a specific conversion function doesSee notes for IMPLICIT and EXPLICIT explanations3-283-293-303-313-32PURPOSE: To change the look of the date to meet requirementsselect last_name, salary, TO_CHAR (hire_date, 'YYYY-Month-DD')from employeeswhere salary = '11000'CHANGE REQUIREMENTThis example is changing it to MM/YYSELECT EMPLOYEE_ID,TO_CHAR (HIRE_DATE, 'MM/YY') Month_HiredFROMEMPLOYEESWHERELAST_NAME like 'H%'NOTE: you control the output format3-33 --4-12Do ThisSELECT EMPLOYEE_ID,TO_CHAR (HIRE_DATE, 'MM/DD/YY')FROMEMPLOYEESWHERELAST_NAME like 'H%'Then thisSELECT EMPLOYEE_ID,TO_CHAR (HIRE_DATE, 'fmMM/DD/YY')HireDateFROMEMPLOYEESWHERELAST_NAME like 'H%'Try fm with a lot of spacesCAN YOU SEE THE DIFFERENCE3-34 – 4-13MANY OTHERSTry out some of them to see what they do3-35-4-14Again another set of formatsREMEMBER:Business uses dates3-37Fm will get rid of leading zeros – see LorentzUsing the TO_CHAR function to add more controlSELECTlast_name,TO_CHAR(hire_date, 'fmDdspth "of" Month YYYY fmHH:MI')FROMemployees==> Try it with 24 hour format and see resultsLAST_NAMETO_CHAR(HIRE_DATE,'FMDDSPTH"OF"MONTHYYYYFMHH:MI')KingSeventeenth of June 1987 12:00KochharTwenty-First of September 1989 12:00De HaanThirteenth of January 1993 12:00HunoldThird of January 1990 12:00ErnstTwenty-First of May 1991 12:00LorentzSeventh of February 1999 12:00MourgosSixteenth of November 1999 12:00RajsSeventeenth of October 1995 12:00DaviesTwenty-Ninth of January 1997 12:00MatosFifteenth of March 1998 12:00Plus more rows3-38Using TO_CHAR with numberSELECTlast_name,TO_CHAR(salary, '$99,999.00') as SALARYFROMemployees;Problems of a floating dollar sign is that the field is left justified as a character field and numbers don't align well.AGAIN SQL wasn't meant to be fancy.BUT right justifies on other softwareLAST_NAMESALARYKing$24,000.00Kochhar$17,000.00De Haan$17,000.00Hunold$9,000.00Ernst$6,000.00Lorentz$4,200.00Convert character string to NUMBER or DATE03-39--4-20General format of conver to a numberSELECTto_number('1234')-2 -- convert STRING of characters to a number less 2from dual;RESUKT:TO_NUMBER('1234')-2------------------- 1232Convert a character to a date4-20Try this:SELECTlast_name, to_char (hire_date, 'DD-Mon-YYYY')from employeeswhere hire_date < to_date ('01-Jan-90', 'DD-Mon-YY');NOTE the results. Is it correct?LAST_NAME TO_CHAR(HIRE_DATE,'DD-MON-YYYY')------------------------- --------------------------------King 17-Jun-1987 Kochhar 21-Sep-1989 De Haan 13-Jan-1993 Hunold 03-Jan-1990 Ernst 21-May-1991 Lorentz 07-Feb-1999 Mourgos 16-Nov-1999 Rajs 17-Oct-1995 Wrong results because it assumed with YY that it was 2090Change it to RRTRY THIS (fx means eXact formatting)Find employees hired on May 24, 1999SELECTlast_name, hire_datefrom employeeswhere hire_date = to_date('May 24, 1999', 'fxMonth DD, YYYY');It is selecting an employee with a specific hire date. The test for equal would not work unless the formats matched. Notice there are spaces between May and 24.NOTE: 1 Repeat the code above, add some extra spaces in the date2 Add some spaces in the format and rerunAdding equal number of spaces in bothSELECTlast_name, hire_datefrom employeeswhere hire_date = to_date('May 24, 1999', 'fxMonth DD, YYYY');RESULT: where are spaces. Using spaces to ensure matching types, but output said just to show name and hire date. What you see is hire date.LAST_NAME HIRE_DATE------------------------- ---------Grant 24-MAY-99 Nesting Functions4-24- Single row functions can be nested to any level- Nested functions evaluate from the innermost or deepest levelExamples of Nesting Functions4-25TRY THIS:Display the - Last name of the employees in department 60- And their new email name -- made up of first 4 characters of last name with _US added- all to appear in uppercase- make the title of column 2 much nicer lookingExample Higgins becomes HIGG_USSELECTlast_name,UPPER (CONCAT(SUBSTR(LAST_NAME, 1, 4) , '_US')) as "Email"FROM EMPLOYEESWHERE DEPARTMENT_ID = 60;LAST_NAMEEmailHunoldHUNO_USErnstERNS_USLorentzLORE_USGeneral Functions04-27Handling NULLSGeneral FormatThe most used is NVLNULL ExamplesPROBLEM 1:List last nameSalaryAnd the result of multiplying salary times commission percentSELECTlast_name, salary, salary*commission_pctFROMemployees;The effect of a NULL value in a calculation is to give a NULL result in displaySome of the outputRajs3500- Davies3100- Matos2600- Vargas2500- Zlotkey105002100Abel110003300Taylor86001720Grant70001050Whalen4400- Hartstein13000- Correction: (might be)SELECTlast_name, salary, salary* nvl(commission_pct,0)FROMemployees;Rajs35000Davies31000Matos26000Vargas25000Zlotkey105002100Abel110003300Taylor86001720Grant70001050Whalen44000Hartstein130000PROBLEM 2:Add up the totals – next chapterNULL with date4-28NVL (hire_date, '01-JAN-2015') if NULL then make it ...NULL with characterSuppose you are missing any value in a character field and you wanted to not leave it as NULL, but wanted it to appear as Unavailable. NVL (city, 'Unavailable' )BAD EXAMPLE … butSELECTlast_name, NVL(to_char(commission_pct), to_char('???'))First needed to convert numeric field to a charater because want to diplay characters (the question mark)FROMemployees;Davies???Matos???Vargas???Zlotkey.2Abel.3Taylor.2Grant.15Whalen???Hartstein???READ the book for the other NULLsCOALESCE4-32 and 4-33Evaluates multiple expressions --- read the bookSELECTlast_name, salary, commission_pct,coalesce( (salary +(commission_pct*salary)), salary + 2000, salary) as "New Salary"FROMemployees;1st value evaluates as a NULL so filled with salary + 20001st value wasn't a null so the calculated expression appears of salary plus salary times commissionDavies3100- 5100Matos2600- 4600Vargas2500- 4500Zlotkey10500.212600Abel11000.314300Taylor8600.210320Grant7000.158050Whalen4400- 6400Hartstein13000- 15000CONDITIONAL EXPRESSIONS4-35CASE applies to ANSI standardDECODE is Oracle syntax (from an earlier period)CASE4-38NOTE: -- ST_MAN as a job_id didn't fit any of the cases so the ELSE took effect and the new salary was just the same as the salaryDECODE -- not using as I prefer case, but you could read it4-39PLEASE READ ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download