agenda – 03/25/2014

27
1 Agenda – 03/25/2014 Login to SQL Server 2012 Management Studio. Answer questions about HW#7 – display answers. Exam is 4/1/2014. It will be in the lab and the database will be the same one used for the SQL homework assignments. Open book, open notes, open web. Not open people. Introduce SQL View database object. Practice using views.

Upload: ora-copeland

Post on 30-Dec-2015

35 views

Category:

Documents


0 download

DESCRIPTION

Agenda – 03/25/2014. Login to SQL Server 2012 Management Studio. Answer questions about HW#7 – display answers. Exam is 4/1/2014. It will be in the lab and the database will be the same one used for the SQL homework assignments. Open book, open notes, open web. Not open people. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Agenda – 03/25/2014

1

Agenda – 03/25/2014

Login to SQL Server 2012 Management Studio.

Answer questions about HW#7 – display answers.

Exam is 4/1/2014. It will be in the lab and the database will be the same one used for the SQL homework assignments. Open book, open notes, open web. Not open people.

Introduce SQL View database object.

Practice using views.

Page 2: Agenda – 03/25/2014

If you did not attend class on 3/13/2014 and did not do SQL Lab 4:

(1) Execute the file called “SQLLab4.sql”. It is located on the k: drive in the IS475\LabFiles folder.You will see errors, and then the tables will create and populate. There are six tables created and populated with this file.

(2) Look at the content of the tables. The database structure is on the next page.

Page 3: Agenda – 03/25/2014

Database for Sample Code in this Presentation

Page 4: Agenda – 03/25/2014

4

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. 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 5: Agenda – 03/25/2014

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 emp.lastname;

Page 6: Agenda – 03/25/2014

6

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 7: Agenda – 03/25/2014

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 8: Agenda – 03/25/2014

8

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 lastname, startwork, hoursworkedFROM VEmpTimeWHERE lastname = 'Polanski';

Page 9: Agenda – 03/25/2014

Using a view is easy!!!

SELECT *FROM vEmpTimeWHERE year(StartWork) = year(getdate()) and month(StartWork) = month(getdate());  SELECT empid,

lastname,description,sum(hoursworked) TotalHoursWorked

FROM vEmpTimeGROUP BY empid,

lastname,description

ORDER BY lastname 

Page 10: Agenda – 03/25/2014

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 – the “shared”

column is the same as using a foreign key between tables.

Page 11: Agenda – 03/25/2014

Let’s go back to that correlated sub-query from Lab 4 (Thursday before Spring Break)

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 xjobtitleON empOuter.jobtitleID = xjobtitle.jobtitleIDWHERE billingrate >

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

Page 12: Agenda – 03/25/2014

The relatively complex correlated subquery on the previous page displays those

employees who have a billing rate that is greater than the billing rate for their job title

Page 13: Agenda – 03/25/2014

13

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 14: Agenda – 03/25/2014

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 SQL function) must

have an alias

Page 15: Agenda – 03/25/2014

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 the actual job title in the SELECT list?

Page 16: Agenda – 03/25/2014

16

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 17: Agenda – 03/25/2014

17

Examples of more complex questions

Which employee worked the most total hours in February?

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?

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

Page 18: Agenda – 03/25/2014

Let’s find out which employee worked the most hours in February of the current year

Where do the columns come from (which tables)?

What is the basic logic of the query?

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

Page 19: Agenda – 03/25/2014

Write the basic logic in pseudocode

SELECT employee stuffFROM timeworkedWHERE sum(timeworked) for

month of February in current year = max(sum(timeworked)) for month of February in current year

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

necessary to accomplish the query.

Page 20: Agenda – 03/25/2014

Use a view to summarize data

CREATE VIEW vEmpHours ASSELECT empID,

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

FROM xtimeworkedGROUP BY empid,

month(startwork)year(startwork)

Look at the result table created by the view:

SELECT *FROM vEmpHours

Page 21: Agenda – 03/25/2014

Look only at those hours in February of the current year:

SELECT *FROM vEmpHoursWHERE monthwork = 2 and yearwork = year(getdate())

Create another view from the view (not necessary, but easier to understand the results):

CREATE VIEW vFebHours ASSELECT *FROM vEmpHoursWHERE monthwork = 2 and yearwork = year(getdate())

Page 22: Agenda – 03/25/2014

Use the view to work on the basic logic

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

Page 23: Agenda – 03/25/2014

Now add the extra data to make the result table “pretty”, piece at a time...

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

FROM vFebHours vFebLEFT OUTER JOIN xemp empon vFeb.empid = emp.empidWHERE totalhours = (SELECT MAX(totalhours)

from vFebHours)

Page 24: Agenda – 03/25/2014

Finish it up!

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

FROM vFebHours vFebLEFT OUTER JOIN xemp empON vFeb.empid = emp.empidLEFT OUTER JOIN xjobtitle jtON jt.jobtitleid = emp.jobtitleidWHERE totalhours = (SELECT MAX(totalhours)

from vFebHours)

Page 25: Agenda – 03/25/2014

25

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 26: Agenda – 03/25/2014

Time to write a few of your own.

1. 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? Don’t use the SELECT TOP 1 statement – do this with a view and a sub-query.

Page 27: Agenda – 03/25/2014

2. What is the name of the client for whom we worked the most time and how much total time have we worked for that client? This one is a little more complicated because the clientID is not directly in the TimeWorked table. Group the TimeWorked table by contractID and then use the Contract table to get the clientID.

Don’t use the SELECT TOP 1 statement in any of the queries.