1 / 44

Queries

Queries. SELECT [DISTINCT] <columnlist> FROM ( <table-list> {<alias>}| <joined table>),... [WHERE <condition>] [GROUP BY <grouping columns> [HAVING <group selection condition>]] [ORDER BY <column name> [<order>],...]. The Basic Query Block.

minda
Télécharger la présentation

Queries

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Queries SELECT [DISTINCT] <columnlist> FROM ( <table-list> {<alias>}| <joined table>),... [WHERE <condition>] [GROUP BY <grouping columns> [HAVING <group selection condition>]] [ORDER BY <column name> [<order>],...]

  2. The Basic Query Block • SELECT identifies what columns will be included (or displayed) in the query result • FROM identifies whichtable(s) to source rows SELECT [DISTINCT] {*,column [alias],...} FROM table

  3. Selecting All Columns, All Rows • The simplest SELECT statement contains the following two clauses: • SELECT clause • Asterisk (*) indicates all columns • FROM clause SELECT * FROM sales_dept

  4. Selecting Specific Columns • List the columns in the SELECT clause. • Separate columns by using a comma. • Specify columns in the order you want them to appear. SELECT dept_id, lname, manager_id FROM sales_emp

  5. Arithmetic Expressions • Create expressions on NUMBER and DATE data types by using operators. • Add + • Subtract - • Multiply * • Divide / e.g., Display the annual salary of employees: SELECT lname, salary * 12, commission FROM sales_emp

  6. Column Aliases • A column alias renames a column heading. • Especially useful with calculations to provide a meaningful column name. • Immediately follows the column name in the SELECT clause. • Optional AS keyword between column name and alias. • Double quotation marks are required if an alias contains spaces, special characters, or is case-sensitive.

  7. Column Aliases • Optional AS keyword between column name and alias. • Double quotation marks are required if an alias contains spaces, special characters, or is case-sensitive. SELECT lname lastname, salary, 12 * salary + 100 FROM sales_emp SELECT lname AS lastname, salary, 12 * salary + 100 AS “new salary” FROM sales_emp

  8. DISTINCT Option • The default display of queries is all rows including duplicate rows. • Eliminate duplicate rows by using DISTINCT in the SELECT clause. SELECT name FROM sales_dept SELECT DISTINCT name FROM sales_dept

  9. DISTINCT Option • DISTINCT applies to all columns in the SELECT list. • When DISTINCT is applied to multiple columns, the result represents the distinct combination of the columns (that is, no two resulting rows will have the same values for all their columns). SELECT DISTINCT dept_id, title FROM sales_emp

  10. ORDER BY Clause • Sort resulting rows with the ORDER BY clause. • ASC – ascending order, default. • DESC – descending order. • ORDER BY clause appears last in a SELECT statement. SELECT lname, dept_id, dstart FROM sales_emp ORDER BY lname

  11. ORDER BY Clause • The default sort order is ascending. • Use DESC to reverse the sort order. • You can sort by expressions or aliases. SELECT lname EMPLOYEE, dstart FROM sales_emp ORDER BY EMPLOYEE DESC • Null values are displayed • Last for ascending sequences. • First for descending sequences.

  12. ORDER BY Clause • You can order by position to save time. SELECT lname, salary * 12 FROM sales_emp ORDER BY 2 • You can sort by multiple columns. SELECT lname, dept_id, salary FROM sales_emp ORDER BY dept_id, salary DESC, commission ASC • The order of ORDER BY list is order of sort. • You can sort by a column that is not in the SELECT list.

  13. WHERE Clause • Restrict the rows returned by the query using the WHERE clause. • Follows the FROM clause. • Conditions consist of the following: • Column name, expression, constant • Comparison operator • Literal SELECT lname, dept_id, salary FROM sales_emp WHERE dept_id = 42

  14. WHERE Clause • Character strings and dates are enclosed within single quotation marks. • Character values are case-sensitive. • The default date format is 'DD-MMM-YY'. SELECT fname, lname, title FROM sales_emp WHERE lname = 'Magee'

  15. R Basic Search Conditions • Comparison. Compare the value of one expression to the value of another expression. • Range. Test whether the value of an expression falls within a specified range of values. • Set membership. Test whether the value of an expression equals one of a set of values. • Pattern match. Test whether a string matches a specified pattern. • Null. Test whether a column has a null (unknown) value.

  16. R Comparison Search Condition • Logical Comparison Operators = > >= < <= • SQL Comparison Operators • BETWEEN ... AND... • IN(list) • LIKE • IS NULL • Logical Operators • AND • OR • NOT

  17. R Comparison Search Condition • Sometimes it is easier to exclude rows you know you do not want. • Logical Comparison Operators != <> ^= • Other SQL Operators • NOT BETWEEN • NOT IN • NOT LIKE • IS NOT NULL

  18. Set Membership Search Condition • Use the [NOT] IN operator to test for values in a list. SELECT id, name, region_id FROM sales_dept WHEREregion_id IN (1,3)

  19. Pattern Match Search Condition • Use the LIKE operator to perform wildcard searches of valid search string values. • Search conditions can contain either literal characters or numbers. • "%" denotes none or many characters. • "_" denotes one character. SELECT lname FROM sales_emp WHERE lname LIKE 'M%'

  20. Pattern Match Search Condition • The LIKE operator can be used as a shortcut for some BETWEEN comparisons. • Pattern matching characters can be combined. SELECT lname, dstart FROM sales_emp WHERE dstart LIKE '%91' SELECT lname FROM sales_emp WHERE lname LIKE '_a%'

  21. NULL Search Condition • Use the IS [NOT] NULL operator to test for null values. • Do not use the = operator. SELECT id, name, credit_rating FROM aless_customer WHERE salesrep_id IS NULL

  22. WHERE Clause: AND / OR • Use AND or OR operators to create complex conditions. • AND requires both conditions to be TRUE. SELECT lname, salary, dept_id, title FROM sales_emp WHERE dept_id = 41 AND title = 'Clerk' • OR requires either condition to be TRUE. SELECT lname, salary, dept_id, title FROM sales_emp WHERE dept_id = 41 OR title = 'Clerk'

  23. Overview of Functions in SQL Use functions to -- • Perform calculations on data. • Modify individual data items. • Manipulate output for groups of rows. • Alter date formats for display. • Convert column data types.

  24. Two Types of SQL Functions • Single row functions • Character • Number • Date • Conversion • Multiple row functions • Group FUNCTION SINGLE ROW FUNCTION MULTI ROW

  25. R Single Row Functions • Manipulate data items. • Accept arguments and return one value. • Act on each row returned. • Return one result per row. • Modify the data type. • Can be nested. function_name (column|expression, [arg1, arg2,...])

  26. Group (Multiple Row) Functions • Also known as aggregate functions. • Operate on a single column of a set of rows in a table. • Return a single value (or a list of values, with one result for each group). • Can be nested.

  27. Group Functions • AVG (DISTINCT|ALL|n) • SUM (DISTINCT|ALL|n) • MAX (DISTINCT|ALL|expr) • MIN (DISTINCT|ALL|expr) • COUNT (DISTINCT|ALL|expr|*)

  28. Group Functions: AVG, SUM • Use AVG and SUM functions to return the average and sum, respectively, of values in a column. • Accept only numeric data types. SELECT AVG(salary), SUM(salary) FROM sales_emp WHERE UPPER(title) LIKE 'SALES%'

  29. Group Functions: MAX, MIN • Use MAX and MIN functions to return the maximum and minimum, respectively, values for a given column. • Accept any data type as argument. SELECT MIN(lname), MAX(lname) FROM sales_emp SELECT MIN(salary), MAX(salary) FROM sales_emp SELECT MIN(dstart), MAX(dstart) FROM sales_emp

  30. Group Functions: COUNT • COUNT(*) returns the number of rows, including nulls and duplicates. SELECT COUNT(*) FROM sales_emp WHERE dept_id = 31

  31. Group Functions: COUNT • COUNT(expression) returns the number of non-null rows. • The use of DISTINCT before the column name eliminates duplicates. SELECT COUNT(commission) FROM sales_emp WHERE dept_id = 31 SELECT COUNT(DISTINCT commission) FROM sales_emp WHERE dept_id = 31

  32. Group Functions • If the SELECT clause includes an aggregate function and no GROUP BY clause is used to group data together, then no item in the SELECT list can include any reference to a column unless that column is the argument to an aggregate function. • The following is an illegal SQL statement: SELECT id, COUNT(commission) FROM sales_emp

  33. Without the GROUP BY Clause SELECT id, lname, dept_id DEPARTMENT FROM sales_emp WHERE dept_id = 41 ID LAST_NAME DEPARTMENT-- --------- ---------- 2 Ngao 41 6 Urguhart 41 16 Maduro 41 17 Smith 41 Department 41 is displayed four times because it appears as the department number of four employees.

  34. With the GROUP BY Clause SELECT dept_id, COUNT(*) ”Number” FROM sales_empWHERE dept_id = 41GROUP BY dept_id DEPT_ID Number ------- ------ 41 4 The GROUP BY clause displays one line of data for each department retrieved in the WHERE clause, and COUNT(*) displays the number of employees in each department (group) displayed.

  35. GROUP BY Clause • List the number of customers in each credit rating. SELECT credit_rating, COUNT(*) AS "# Customers" FROM sales_customer GROUP BY credit_rating

  36. GROUP BY Clause • List all job titles and the total monthly salary for each job title. SELECT title, SUM(salary) PAYROLL FROM sales_emp WHERE title NOT LIKE 'VP%' GROUP BY title ORDER BY SUM(salary)

  37. GROUP BY Clause • All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. • The GROUP BY column does not have to be in the SELECT clause. SELECT title, MAX(salary) FROM sales_emp GROUP BY title

  38. GROUP BY Clause • Any expression in the SELECT list that is not a group function must be listed in the GROUP BY clause. Otherwise, an error message will be displayed SELECT region_id, COUNT(name) FROM sales_dept ORA-00937: (region_id) not a single- group group function

  39. GROUP BY Clause • Return summary results for groups and subgroups by listing more than one column in the GROUP BY clause. • Determine the default sort order of the results by the order of the columns in the GROUP BY clause. SELECT dept_id, title, COUNT(*) FROM sales_emp GROUP BY dept_id, title

  40. GROUP Functions • WHERE clause cannot be used to restrict groups. Use the HAVING clause. SELECT dept_id, AVG(salary) FROM sales_emp WHERE AVG(salary) > 2000 GROUP BY dept_id ORA-00934: group function is not allowed here

  41. Recall: WHERE Clause • Used to select rows to be displayed. SELECT lname, titleFROM sales_empWHERE lname LIKE ’V%’ Restrict Rows LNAME TITLE--------- -----------------Velasquez President Display a specific employee as restricted in the WHERE clause

  42. HAVING Clause • Used to restrict groups. • Step 1: Rows (that passed the WHERE condition) are grouped. • Step 2: The group function is applied to each of the groups. • Step 3: Groups matching the HAVING condition are displayed. • Column names used in the HAVING clause must also appear in the GROUP BY clause or be contained in the group functions.

  43. HAVING Clause SELECT title, TO_CHAR(12 * AVG(salary), ‘$99,999.99’) ”ANNUAL SALARY”, COUNT(*) ”NUMBER OF EMPLOYEES”FROM sales_empGROUP BY title HAVING COUNT(*) > 2 TITLE ANNUAL SALARY NUMBER OF EMPLOYEES-------------------- -------------- -------------------Sales Representative $17,712.00 5Stock Clerk $11,388.00 10Warehouse Manager $14,776.80 5 Display specific groups of job titles as restricted in the HAVING clause.

  44. HAVING Clause • The GROUP BY clause can be used even without using a group function in the SELECT clause. • To restrict rows based on the result of a group function, use a GROUP BY clause and a HAVING clause. SELECT dept_id FROM sales_emp GROUP BY dept_id HAVING SUM(salary) > 4000

More Related