Top Banner
Querying and Reporting Module 3
39
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Module03

Querying and Reporting

Module 3

Page 2: Module03

• Arithmetic operators used in SQL• Built in Functions• Retrieving data with the select statements• Grouping Results sets• Joins• Sub queries

Learning Objectives

Page 3: Module03

At the end of this section, you should be able to work with:• Arithmetic operators used in SQL

• Built in Functions– String Functions– Date Functions– System Functions– Aggregate Functions

• Retrieving data with the select statements– Based on Conditions– Limit Results

Module 3 : Agenda

Page 4: Module03

Module 3 : Agenda• Grouping Results sets

– Group by– Compute and Compute By

• Joins– Natural Join– Equi Join– Self Join– Outer Join

• Sub queries– In– Exists– Correlated sub queries

Page 5: Module03

SELECT Statement

Use the SELECT statement to retrieve data from one or more tables:

• SELECT <column(s) >

• FROM <table>

• [WHERE <condition>]

• [ORDER BY <column(s) [ASC|DESC]>]

table is the name of the table

column is the name of the column in the table to be selected

condition identifies the rows to be selected and is composed of column names, expressions, constraints, sub-queries and comparison operators

column is the name of the column(s) used for sorting(order by)

Page 6: Module03

Querying and Reporting• Selection : Querying for selection retrieves a subset of the rows in one or

more tables.– Example

• Projection : Querying for projection retrieves a subset of the columns in one or more tables.

• It is best to put each column chosen in a separate line– Example

SELECT * FROM emp

SELECT empno,ename,deptno

FROM emp

Page 7: Module03

• Rearranging order of columns: – Example

• Using Column aliases– Example

SELECT ename as [Employee Name],empno,deptno

FROM emp

SELECT empname,eno,deptno

FROM emp

Querying and Reporting (Continued)

Page 8: Module03

Arithmetic Operators

Operator Operation

+ Addition

- Subtraction

/ Division

* Multiplication

% Modulo

Page 9: Module03

Built in Functions

• Built in Functions are a T-SQL extension to SQL– String Functions– Date Functions– System Functions– Aggregate Functions

Page 10: Module03

Built In Functions : String Functions

Functions Descriptions

ascii (char_expr) Returns the ASCII code for the first character in the expression.

char_length (char_expr) Returns an integer representing the number of characters in a character expression or text value.

reverse (expression) Returns the reverse of the character or binary expression

substring (expression, start, length) Returns part of a string. Start specifies the character position at which the substring begins. length specifies the number of characters in the substring.

Page 11: Module03

Built In Functions : Date Functions

Functions Descriptions

getdate () Returns Current system date and time.

datepart (datepart, date) Returns part of date as an integer.

datediff (datepart, date, date) Returns the time between the first and second date. You can specify the datepart as months, years, hours, etc.

dateadd (datepart, number, date) Returns date produced by adding datepart to given date.

Page 12: Module03

Built In Functions : System Functions

Functions Descriptions

host_id ( ) Returns the process id of the process.

Host_name () Returns the computer name

datalength (expression) Returns the length of the column

Page 13: Module03

Use of Aggregate Functions

• Aggregate functions are used to summarize the data retrieved in a query.

Aggregate Function Description

Sum ([all | distinct] expression) Total of the (distinct) values in the expression

Avg ([all | distinct] expression) Average of the (distinct) values in the expression

Count ([all | distinct] expression)

Number of (distinct) non-null values in the expression

count(*) Number of selected rows – including null values

Max (expression) Highest value in the expression

Min (expression) Lowest value in the expression

Page 14: Module03

Selecting Rows – Search Based

• The method of restriction is the basis of the WHERE clause in SQL

• Character strings and dates in the WHERE clause must be enclosed in single quotation marks (‘)

Page 15: Module03

Rows may be limited by:

• EQUALS CONDITION– Display rows based on an exact match of values

SELECT LastName,

Salary FROM Employee WHERE Salary = 30000

SELECT EmployeeId, LastName

FROM Employee WHERE ManagerName = ‘RAYMOND’

Page 16: Module03

Rows may be limited by: (Continued)

• >, <, <=, >= or <> CONDITION

SELECT LastName

FROM Employee WHERE Salary > 30000

SELECT EmployeeId, LastName

FROM Employee WHERE Salary <= 30000

SELECT EmployeeId

FROM Employee WHERE Status <> ‘ACTIVE’

Page 17: Module03

Rows may be limited by: (Continued)

• BETWEEN CONDITION– Display rows based on a range of values

SELECT LastName

FROM Employee WHERE Salary BETWEEN 30000 AND 50000

• IN CONDITION– Display rows based on a list of values

SELECT EmployeeIdFROM Employee WHERE ManagerId IN (100, 200, 300)

Page 18: Module03

Rows may be limited by: (Continued)

• LIKE CONDITION– Performs wildcard searches of valid search string values– Can contain either literal characters or numbers

• % denotes zero or many characters

• _ denotes one character

– Use ESCAPE identifier to search for the actual % and _symbols

SELECT LastName

FROM Employee WHERE LastName LIKE ‘%ram’

SELECT LastName

FROM Employee WHERE LastName LIKE ‘_at’

Page 19: Module03

Rows may be limited by: (Continued)

• LOGICAL CONDITION– AND, OR, NOT

SELECT LastName, JobId

FROM Employee WHERE Salary <=15000 AND JobId = ‘SE’

SELECT LastName, JobId

FROM Employee WHERE Salary <= 15000 OR JobId = ‘SE’

Page 20: Module03

Rows may be limited by: (Continued)

• LOGICAL CONDITION– AND, OR, NOT

SELECT LastName, JobId

FROM Employee WHERE Salary <=15000 AND NOT JobId = ‘SE’

Page 21: Module03

Rows may be limited by: (Continued)

• Distinct

• Top

• Percent

SELECT distinct au_id, FROM titleauthor

SELECT Top(4) * FROM titleauthor

SELECT Top 20 percent *FROM titleauthor

Page 22: Module03

Sorting Rows

• ORDER BY clause– ASC specifies an ascending order– DESC specifies a descending order

SELECT LastName, Salary, JobId

FROM Employee ORDER BY Salary DESC, JobId ASC

• Display the result in descending order by the attribute salary

• If two records have the same attribute value, the salary sorting criteria is in ascending order according to the attribute values of JobId

Page 23: Module03

• Group By – A group by expression can contain column names not present in the select list.

Grouping Result Sets

SELECT type, avg(price), sum(ytd_sales)

FROM titlesGroup by pub_id, type

Page 24: Module03

• Compute clause provides a detail and summary rows with one select statement.

• You can calculate more than one row aggregate.

Grouping Result Sets

SELECT type, price, advance

FROM titlesOrder by typeCompute sum(price), sum(advance)

SELECT type, price, advance

FROM titlesOrder by typeCompute sum(price), sum(advance) By type

Page 25: Module03

Joins

• Joins compare two or more tables or views by specifying compare column.

• It checks values in these columns row wise and links the rows with the matching values.

• Joins can be applied to the tables of the own database or other databases (with select permissions)

Page 26: Module03

start of select, update, insert, delete, or subquery

from {table_list | view_list}

where [not]

[table_name. | view_name.]column_name join_operator

[table_name. | view_name.]column_name

[{and | or} [not]

[table_name.|view_name.]column_name join_operator

[table_name.|view_name.]column_name]...

End of select, update, insert, delete, or subquery

Joins - Syntax

Page 27: Module03

Joins – Cross Join

• When a join is applied without the WHERE clause it produces the Cartesian product of the tables involved in that join.

USE AdventureWorks GO

SELECT p.SalesPersonID, t.Name AS Territory

FROM Sales.SalesPerson pCROSS JOIN Sales.SalesTerritory tORDER BY p.SalesPersonID;

Page 28: Module03

Joins – Equi Join and Natural Join

• Joins based on equality are called as Equi Joins

• When an Equi-join returns all the columns of both the tables it is known as Natural Join

SELECT au_fname, pub_nameFROM Authors, PublishersWhere Authors.city=Publishers.city

SELECT *FROM Authors, PublishersWhere Authors.city=Publishers.city

Page 29: Module03

Joins – Self Join

• When a join compares values within the same column of one table are called as self joins.

USE pubs; GO

select au1.au_fname,

au2.au_fname,

from authors au1,

authors au2

where au1.city = "Oakland" and au2.city = "Oakland"

and au1.state = "CA" and au2.state = "CA"

and au1.postalcode = au2.postalcode

Page 30: Module03

Joins – Outer Join

• Outer joins include all the rows regardless of whether there are matching rows.

• Outer Joins are of 3 types– Left Outer– Right Outer– Full Outer

SELECT *FROM titlesLEFT JOIN titileauthor ON titiles.title_id = titleauthor.title_id

Page 31: Module03

Joins – Outer Join

SELECT *FROM titlesRIGHT JOIN titileauthor ON titiles.title_id = titleauthor.title_id

SELECT *FROM titlesFULL OUTER JOIN titileauthor ON titiles.title_id = titleauthor.title_id

Page 32: Module03

Sub Queries• A subquery is nested select statement in another

select/insert/update/delete statement as a condition.

• A subquery can be used as an expression.

• When subquery can be evaluated as if it were an independent query it is called a Non correlated subquery.

• When a subquery can not be evaluated as an independent query, but can reference columns in a table listed in the from list of the outer query, it is called a correlated subquery.

• There are two types of subqueries– Expression subqueries– Quantified predicate subqueries

Page 33: Module03

Sub Queries (Continued)

• Expression subqueries: The value retuned is always single value which is further used for comparison.

SELECT title,price

FROM titlesWHERE price =(SELECT priceFROM titlesWHERE title = 'Straight Talk About Computers')

Page 34: Module03

Sub Queries (Continued)

• Quantified predicate subqueries: The value returned can range from 0..n. This query operates on lists introduced with IN or with a comparison operator. Further it can be used as an existence test with the EXISTS introduced with exists.– Subqueries with IN

SELECT pub_name

FROM publishers

WHERE pub_id IN

(SELECT pub_id

FROM titles

WHERE type = ‘business’)

Page 35: Module03

– Subqueries with Exists

Sub Queries (Continued)

SELECT pub_name

FROM publishers

WHERE EXISTS

(SELECT *

FROM titles

WHERE pub_id = publishers.pub_id

AND type = ‘business’)

Page 36: Module03

– Correlated Subqueries

Sub Queries (Continued)

SELECT table1.type

FROM titles table1

WHERE table1.type

IN

(SELECT table2.type

FROM titles table2

WHERE table1.pub_id != table2.pub_id )

Page 37: Module03

You may find useful content on T-SQL joins on the following url:• Web sites:

– http://www.sqlteam.com/article/writing-outer-joins-in-t-sql– http://www.sqlmag.com/Article/ArticleID/5342/sql_server_5342.html– http://pietschsoft.com/post/2005/12/T-SQL-Join-Tables-by-a-Field-th

at-contains-a-delimited-string.aspx– ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/udb9/html/c4f98374-

e8a7-4f73-8d0e-309bd94ad1ae.htm

Resources

Page 38: Module03

Key Points

• SQL is an industry standard language for updating to, and getting information from, a database.

• The basic and most common SQL statements are: SELECT, INSERT, UPDATE, DELETE.

Page 39: Module03

Questions & Comments