Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement."— Presentation transcript:

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

2 Database for Sample Code 2

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. 3

4 4 Selectworker.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" FROMxempworker LEFT OUTER JOINxempmanager ONworker.managerid = manager.empid LEFT OUTER JOIN xJobTitle jobtitle ONworker.jobtitleid = jobtitle.jobtitleid ORDER BY worker.lastname

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!! 5

6 Using a view is easy!!! 6 SELECT* FROMvEmpInfo; SELECT* FROMvEmpInfo WHEREyear(EmployeeHireDate) = year(getdate()); SELECTemployeeid, employeename, employeejobtitle, managername FROMvEmpInfo WHEREyear(EmployeeHireDate) = year(getdate());

7 Joining tables with a view is a little harder… 7 SELECTcontractid, clientid, DateSigned, EmployeeName 'Contract Manager', EmployeeJobTitle, EmployeeBillingRate FROMxContract contract LEFT OUTER JOIN vEmpInfo ONcontract.contractmgrid = vempinfo.employeeid

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

9 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: SELECTISNULL(emp.empid,tw.empid) empid, emp.lastname, tw.contractid, tw.startwork, tw.worktypeid, work.description, ISNULL(minutes/60,0) FROMxemp emp FULL OUTER JOINxtimeworked tw ONemp.empid = tw.empid LEFT OUTER JOINxwork work ONwork.worktypeid = tw.worktypeid ORDER BY 1; 9

10 10 Create a view out of the code CREATE VIEW vEmptime AS SELECTISNULL(emp.empid,tw.empid) empid, emp.lastname, tw.contractid, tw.startwork, tw.worktypeid, work.description, ISNULL(minutes/60,0) hoursworked FROMxemp emp FULL OUTER JOINxtimeworked tw ONemp.empid = tw.empid LEFT OUTER JOINxwork work ONwork.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

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 * FROMVEmpTime ORDER BYempid; SELECT * FROM VEmpTime WHEREhoursworked = 0; SELECTlastname FROMVEmpTime; 11

12 Can a view be joined with tables? SELECTVEmpTime.empid, VEmpTime.lastname, VEmpTime.startwork, VEmpTime.contractid, client.name FROMVEmpTime INNER JOINxcontract contract ONcontract.contractid = VEmpTime.contractid INNER JOINxclient client ONcontract.clientid = client.clientid ORDER BYVEmpTime.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. 12

13 Last week in lab, we discussed a correlated sub-query 13 SELECTempID, lastname, empOuter.jobtitleID, title, billingrate "Employee Billing Rate", (SELECTAVG(billingrate) FROMxemp empSelect WHEREempOuter.jobtitleID = empSelect.jobtitleID) "Average Billing Rate" FROMxemp empOuter LEFT OUTER JOINxjobtitle jobtitle ONempOuter.jobtitleID = jobtitle.jobtitleID WHEREbillingrate > (SELECT AVG(billingrate) FROMxemp empInner WHEREempOuter.jobtitleID = empInner.jobtitleID)

14 That subquery displays those employees who have a billing rate that is greater than the billing rate for their job title 14

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. 15

16 Create a “view” database object 16 CREATE VIEW vAvgRateByTitle AS SELECTjobtitleID, AVG(billingrate) AverageBillRate FROMxemp GROUP BY jobtitleID; Remember: when using a VIEW, any derived column (calculated, aggregate and/or with a SQL function) must have an alias

17 Look at the VIEW results and use the VIEW in another query 17 SELECT * FROMvAvgRateByTitle; SELECTemp.empid, emp.lastname, emp.billingrate, emp.jobtitleid, vAvgRateByTitle.AverageBillRate FROMxempemp LEFT JOINvAvgRateByTitle ONemp.jobtitleid = vAvgRateByTitle.jobtitleid WHEREemp.billingrate > AverageBillRate; How would you add in the actual job title in the SELECT list?

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. 18

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? 19

20 Let’s find out which employee worked the most hours in September 20 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?

21 Write the basic logic in pseudocode 21 SELECT employee stuff FROM timeworked WHEREsum(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.

22 Use a view to summarize data 22 CREATE VIEW vEmpHours AS SELECT empID, month(startwork) MonthWork, sum(minutes/60) TotalHours FROMxtimeworked GROUP BY empid, month(startwork)

23 Maybe create another view if you want... 23 CREATE VIEW vEmpHoursSept AS SELECT* FROMvEmphours WHEREmonthwork = 9;

24 Use the view to work on the basic logic 24 SELECT * FROM vEmpHoursSept WHERE totalhours = (SELECT MAX(totalhours) FROM vEmpHoursSept)

25 Now add the “extra” stuff, piece at a time... 25 SELECTvEHS.empid, firstname + ' ' + lastname "Employee Name", officephone, totalhours FROM vEmpHoursSept vEHS LEFT OUTER JOIN xemp emp on vEHS.empid = emp.empid WHERE totalhours = (SELECT MAX(totalhours) from vempHourssept)

26 Finish it up! 26 SELECTvEHS.empid, firstname + ' ' + lastname "Employee Name", officephone, description, totalhours FROM vEmpHoursSept vEHS LEFT OUTER JOIN xemp emp on vEHS.empid = emp.empid LEFT OUTER JOIN xjobtitle jt on jt.jobtitleid = emp.jobtitleid WHERE totalhours = (SELECT MAX(totalhours) from vempHourssept)

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. 27

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. 28

29 Build two tables for UNION example 29 Download and execute: k:\IS475\CreateBuildUnionExampleTables.sql

30 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?

31 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

32 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.

33 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 custname FROM tblcurrentcustomer UNION ALL SELECT custname FROM tbloldcustomer ORDER BY custname;

34 Example of an INTERSECT statement What if you want to look only at those rows that are common to both queries? 34 SELECT custname FROM tblcurrentcustomer INTERSECT SELECT custname FROM tbloldcustomer ORDER BY custname;

35 What if you want to see a list of customers and products together? SELECT custname FROM tblcurrentcustomer UNION SELECT description FROM tblitem ORDER BY 1 ; 35 Can combine any “like” queries

36  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?


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

Similar presentations


Ads by Google