36
1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement.

1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Embed Size (px)

Citation preview

Page 1: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

1

Agenda – 10/24/2013

Answer questions from lab on 10/22.

Present SQL View database object.

Present SQL UNION statement.

Page 2: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Database for Sample Code

xEmp

PK EmpID

LastName FirstName Address City State Zip HireDate OfficePhone BillingRateFK1 ManagerIDFK2 JobTitleID

xTimeWorked

PK TimeWorkedID

StartWork MinutesFK1 EmpIDFK2 WorkTypeIDFK3 ContractID

xWork

PK WorkTypeID

StdBillRate Description

allocates

xContract

PK ContractID

FK1 ClientID DateSigned DateDueFK2 ContractMgrID

xClient

PK ClientID

Name Address City State Zip Phone Fax ContactNameFK1 ClientTypeID

places

allocates

allocates

manages

xJobTitle

PK JobTitleID

Title

has

xEstimatedTime

PK,FK1 WorkTypeIDPK,FK2 ContractID

EstHours

is for

is for

xClientType

PK ClientTypeID

ClientTypeDescription

has

is managed by

Page 3: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

3

What is a SQL View?

A “virtual” table. A set of SQL statements that creates a result table which can

be accessed by other SQL statements. Similar to a function in another programming language, except

that the end-product of the view is a named result table. A database object.

The code for a view is stored in the database. A view contains no data of its own. A view relies on the data in the base tables used to create the

view. A set of stored SQL code.

Stores code; not data.

Page 4: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Select worker.empid "EmployeeID",worker.lastname + ', ' + substring(worker.firstname,1,1) + '.' "EmployeeName",worker.jobtitleid 'WorkerJobTitleID',jobtitle.jobtitleid 'JobTitleID',ISNULL(jobtitle.title, 'Missing Job Title') 'EmployeeJobTitle',worker.hiredate 'EmployeeHireDate',worker.billingrate 'EmployeeBillingRate',worker.managerid "ManagerEmployeeID",ISNULL(manager.lastname + ', ' + substring(manager.firstname,1,1) + '.', 'No Manager')

"ManagerName"

FROM xemp workerLEFT OUTER JOIN xemp managerON worker.managerid = manager.empidLEFT OUTER JOIN xJobTitle jobtitleON worker.jobtitleid = jobtitle.jobtitleidORDER BY worker.lastname

Page 5: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

5

Creating a view is easy!!

CREATE VIEW viewname AS

Make sure that all fields in the SELECT list using any kind of function, calculation or conditional logic has an appropriate alias (without spaces in the alias)

Remove ORDER BY statement

Run it!!

Page 6: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

6

Using a view is easy!!!

SELECT *FROM vEmpInfo;

 SELECT *FROM vEmpInfoWHERE year(EmployeeHireDate) = year(getdate());  SELECT employeeid,

employeename,employeejobtitle,managername

FROM vEmpInfoWHERE year(EmployeeHireDate) = year(getdate()); 

Page 7: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

7

Joining tables with a view is a little harder…

SELECT contractid,clientid,DateSigned,EmployeeName 'Contract Manager',EmployeeJobTitle,EmployeeBillingRate

FROM xContract contractLEFT OUTER JOIN vEmpInfoON contract.contractmgrid = vempinfo.employeeid

Page 8: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Figuring out when to use a view and what to do with a view is

much harder

Page 9: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Let’s say we frequently look at all the information about time in our database and we always convert the time to hours and we always like to include the name of the employee who worked

the time as well as the description of the type of work performed:

SELECT ISNULL(emp.empid,tw.empid) empid,

emp.lastname,

tw.contractid,

tw.startwork,

tw.worktypeid,

work.description,

ISNULL(minutes/60,0) FROM xemp empFULL OUTER JOIN xtimeworked tw ON emp.empid = tw.empidLEFT OUTER JOIN xwork workON work.worktypeid = tw.worktypeidORDER BY 1;

Page 10: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Create a view out of the code

CREATE VIEW vEmptime ASSELECT ISNULL(emp.empid,tw.empid) empid,

emp.lastname,

tw.contractid,

tw.startwork,

tw.worktypeid,

work.description,

ISNULL(minutes/60,0) hoursworkedFROM xemp empFULL OUTER JOIN xtimeworked tw ON emp.empid = tw.empidLEFT OUTER JOIN xwork workON work.worktypeid = tw.worktypeid;

Must eliminate the ORDER BY

clause

Must add the CREATE VIEW

statement

Must alias any field with a calculation,

aggregation or function

Page 11: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

11

How is the view used via SQL?

Views are used just as tables are used in SQL. In this example, the join is predefined, so it is easier to write queries to access the data.

SELECT * FROM VEmpTimeORDER BY empid;

SELECT *FROM VEmpTimeWHERE hoursworked = 0;

SELECT lastnameFROM VEmpTime;

Page 12: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Can a view be joined with tables?

SELECT VEmpTime.empid,VEmpTime.lastname,VEmpTime.startwork,VEmpTime.contractid,client.name

FROM VEmpTimeINNER JOIN xcontract contractON contract.contractid = VEmpTime.contractidINNER JOIN xclient clientON contract.clientid = client.clientidORDER BY VEmpTime.empid,

VEmpTime.contractid desc;

Must have a “shared” column to access the data between tables and view – same as using

a foreign key between tables.

Page 13: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Last week in lab, we discussed a correlated sub-query

SELECT empID,lastname,empOuter.jobtitleID,title,billingrate "Employee Billing Rate",(SELECT AVG(billingrate)

FROM xemp empSelect WHERE empOuter.jobtitleID = empSelect.jobtitleID)

"Average Billing Rate" FROM xemp empOuterLEFT OUTER JOIN xjobtitle jobtitleON empOuter.jobtitleID = jobtitle.jobtitleIDWHERE billingrate >

(SELECT AVG(billingrate) FROM xemp empInner WHERE empOuter.jobtitleID = empInner.jobtitleID)

Page 14: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

That subquery displays those employees who have a billing rate that is greater than the

billing rate for their job title

Page 15: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

15

Group Functions and Joins are Complex

Must have all non-group attributes that are in the SELECT list also in the GROUP BY statement.

Difficult to do a group function of a group function. Examples:

The maximum of the sum of hours.

The minimum of a count of products.

Joining multiple tables can yield full or partial cartesian products making it difficult to trouble-shoot the SQL code.

Page 16: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Create a “view” database object

CREATE VIEW vAvgRateByTitleASSELECT jobtitleID,

AVG(billingrate) AverageBillRateFROM xempGROUP BY jobtitleID;

Remember: when using a VIEW, any derived column (calculated, aggregate and/or with a

SQL function) must have an alias

Page 17: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Look at the VIEW results and use the VIEW in another query

SELECT *FROM vAvgRateByTitle;

SELECT emp.empid,emp.lastname,emp.billingrate,emp.jobtitleid,vAvgRateByTitle.AverageBillRate

FROM xemp empLEFT JOIN vAvgRateByTitleON emp.jobtitleid = vAvgRateByTitle.jobtitleidWHERE emp.billingrate > AverageBillRate;

How would you add in the actual job title in the SELECT list?

Page 18: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

18

So, what’s the big deal?

Views allow you to break down difficult queries into smaller pieces for easier design, coding and debugging.

Views allow you to create a layer of abstraction between the data structure and the user or programmer allowing greater security. Programmers do not know the structure of the base tables. Less

risk of fraud. Users can see “pre-joined” tables for their queries. Users don’t have to understand the complexity of the actual

database. No one sees data that is secure (salary, for example).

Views allow you to access the results of aggregate functions more easily.

Page 19: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

19

Examples of more complex questions

Which employee worked the most total hours in September?

What is the description of the work type with the most time in the time table and how much time was reported for that work type description?

For which contract have we spent the most time?

What is the name of the client for whom we worked the most time during the month of August in the current year?

Which contracts have had more time worked than the estimated time?

Which contracts have more than 25% time worked than the estimated time?

Page 20: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Let’s find out which employee worked the most hours in September

Where do the columns come from (which table)?

What is the basic logic of the query?

What is the simplest component that can be written to accomplish the basic logic?

Page 21: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Write the basic logic in pseudocode

SELECT employee stuffFROM timeworkedWHERE sum(timeworked) for month of September =

max(sum(timeworked)) for month of September

This code doesn’t work!! It is just written to get an understanding of the basic logic

necessary to accomplish the query.

Page 22: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Use a view to summarize data

CREATE VIEW vEmpHours ASSELECT empID,

month(startwork) MonthWork,sum(minutes/60) TotalHours

FROM xtimeworkedGROUP BY empid,

month(startwork)

Page 23: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Maybe create another view if you want...

CREATE VIEW vEmpHoursSept ASSELECT *FROM vEmphoursWHERE monthwork = 9;

Page 24: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Use the view to work on the basic logic

SELECT * FROM vEmpHoursSept WHERE totalhours = (SELECT MAX(totalhours) FROM vEmpHoursSept)

Page 25: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Now add the “extra” stuff, piece at a time...

SELECT vEHS.empid,firstname + ' ' + lastname "Employee Name",officephone,totalhours

FROM vEmpHoursSept vEHSLEFT OUTER JOIN xemp empon vEHS.empid = emp.empidWHERE totalhours = (SELECT MAX(totalhours)

from vempHourssept)

Page 26: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Finish it up!

SELECT vEHS.empid,firstname + ' ' + lastname "Employee Name",officephone,description,totalhours

FROM vEmpHoursSept vEHSLEFT OUTER JOIN xemp empon vEHS.empid = emp.empidLEFT OUTER JOIN xjobtitle jt on jt.jobtitleid = emp.jobtitleid WHERE totalhours =

(SELECT MAX(totalhours) from vempHourssept)

Page 27: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

27

Conclusion: Uses of views

Views are used to: Provide easier access to data. Enhance security. Lessen the visible complexity of the database.

Views are usually created by the DBA for a defined workgroup of people. Programmers. Users. Users in a specific functional area.

Page 28: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

28

Course Agenda: 10/29/2013

Learn how to use the SQL UNION statement.

Do together as a class.

Practice writing SQL with the test database (database is also used for HW#8)

Do individually.

Page 29: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

29

Build two tables for UNION example

Download and execute:

k:\IS475\CreateBuildUnionExampleTables.sql

Page 30: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

A way to combine the result tables of separate SQL statements.

Not really a “JOIN” statement.

Does not combine underlying tables, as a JOIN statement.

Combines result tables into a single result table.

Produces a table of the concatenated results from SELECT statements.

30

What is a SQL UNION?

Page 31: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Imagine that we have two tables: A table containing our current customers (tblcurrentcustomer) and a table containing our past customers (tbloldcustomer).

Imagine that we want to have a combined list of the names of both our current and old customers.

31

Example of a UNION statement

Page 32: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

SELECT custname

FROM tblcurrentcustomer

UNION

SELECT custname

FROM tbloldcustomer;

The UNION statement eliminates any rows that are duplicated between the two result

tables. It checks for duplication on the requested column or columns.

Page 33: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

What if you want to see all of the rows in the result tables of the two select statements whether or not there are duplications?

33

Example of a UNION ALL statement

SELECT custnameFROM tblcurrentcustomerUNION ALLSELECT custnameFROM tbloldcustomerORDER BY custname;

Page 34: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Example of an INTERSECT statement

What if you want to look only at those rows that are common to both queries?

34

SELECT custnameFROM tblcurrentcustomerINTERSECTSELECT custnameFROM tbloldcustomerORDER BY custname;

Page 35: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

What if you want to see a list of customers and products together?

SELECT custnameFROM tblcurrentcustomerUNIONSELECT descriptionFROM tblitem

ORDER BY 1;

35

Can combine any “like” queries

Page 36: 1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement

Must have the same number of columns in the select lists of the queries that are combined.

The columns must be of the same type when compared column-by-column in the select lists of the queries that are combined.

The name(s) of the columns are taken from the first query.

The ORDER BY clause is best used with positioning rather than the name(s) of columns. Example: ORDER BY 1;

36

So, what are the rules?