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.

Slides:



Advertisements
Similar presentations
4d. Structured Query Language – JOIN Operation Lingma Acheson Department of Computer and Information Science IUPUI CSCI N207 Data Analysis with Spreadsheets.
Advertisements

Technical BI Project Lifecycle
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Aggregates.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Aggregates.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 5: Subqueries and Set Operations.
Chapter 11.1 and 11.2 Data Manipulation: Relational Algebra and SQL Brian Cobarrubia Introduction to Database Management Systems October 4, 2007.
SQL for Data Retrieval. Save your SQL Scripts When working with SQL Management Studio, you should keep saving your scripts as a.sql file to somewhere.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Download three SQL script files from wiki page.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 8: Subqueries.
SQL 資料庫查詢語言 取材自 EIS, 3 rd edition By Dunn et al..
Learningcomputer.com SQL Server 2008 – Entity Relationships in a Database.
Banner and the SQL Select Statement: Part Four (Multiple Connected Select Statements) Mark Holliday Department of Mathematics and Computer Science Western.
General Programming Introduction to Computing Science and Programming I.
 Continue queries ◦ You completed two tutorials with step-by-step instructions for creating queries in MS Access. ◦ Now must apply knowledge and skills.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-column subqueries, Multiple-row Subqueries, Correlated Subqueries 11/2/10,
1 Agenda for Class 03/07/2006  Learn to simplify queries for complex questions through the use of views.  Concept of a view.  Syntax to create and access.
One-to-many relationship Relational databases link several entities based on relationships that exist (based on modeling reality) 1:m relationship example:
IS201 Agenda: 10/15/2013 Do form and report exercise. Identify general guidelines for form and report design. Discuss a few key points about reports in.
 Agenda 2/20/13 o Review quiz, answer questions o Review database design exercises from 2/13 o Create relationships through “Lookup tables” o Discuss.
Database Systems Microsoft Access Practical #3 Queries Nos 215.
Oracle DML Dr. Bernard Chen Ph.D. University of Central Arkansas.
Agenda for 02/21/2006 Learn how to use more than one table in a query. Discuss how DBMS processes multiple tables. Explain the different types of joins.
1 Agenda – 10/24/2013 Answer questions from lab on 10/22. Present SQL View database object. Present SQL UNION statement.
Views Lesson 7.
1 Agenda for Class 03/02/2006  Do SQL join “quiet participation” exercise in class.  Learn to simplify queries for complex questions through the use.
Day 13, Slide 1 U:/msu/course/cse/103 CSE 103 Students: Review INNER and OUTER JOINs, Subqueries. Others: Please save your.
XP Chapter 3 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Analyzing Data For Effective Decision Making Chapter.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
SQL for Data Retrieval. Running Example IST2102 Data Preparation Login to SQL server using your account Select your database – Your database name is.
INFO1408 Database Design Concepts Week 15: Introduction to Database Management Systems.
Intro to SQL Management Studio. Please Be Sure!! Make sure that your access is read only. If it isn’t, you have the potential to change data within your.
1 Chapter 10 Joins and Subqueries. 2 Joins & Subqueries Joins – Methods to combine data from multiple tables – Optimizer information can be limited based.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Agenda for 02/16/2006 Answer any questions about SQL project. Do you want to see any of the answers for the queries? Discuss additional formatting options.
STRUCTURED QUERY LANGUAGE SQL-II IST 210 Organization of Data IST210 1.
STRUCTURED QUERY LANGUAGE SQL-III IST 210 Organization of Data IST210 1.
While you are waiting for class to start... (1) Login to SQL Server 2012 Management Studio (2) Execute the file called “SQLLab3.sql”. It is located on.
SQL for Data Retrieval. Save your SQL Scripts When working with SQL Management Studio, you should keep saving your scripts as a.sql file to somewhere.
Instructor: Craig Duckett Lecture 03: Tuesday, April 14, 2015 SQL Sorting, Aggregates and Joining Tables 1.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
While you are waiting for class to start... (1)Login to SQL Server 2012 Management Studio (2) Execute the file called “SQLLab4.sql”. It is located on the.
IS201 Agenda: 09/19  Modify contents of the database.  Discuss queries: Turning data stored in a database into information for decision making.  Create.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Aliya Farheen October 29,2015.
Agenda for Class 2/20/2014 Introduce Microsoft’s SQL Server database management system. Use the lab to discuss how to CREATE, DROP and populate (INSERT)
(SQL - Structured Query Language)
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
LINQ to DATABASE-2.  Creating the BooksDataContext  The code combines data from the three tables in the Books database and displays the relationships.
# 1# 1 QueriesQueries How do we ask questions of the data? What is SELECT? What is FROM? What is WHERE? What is a calculated field? Spring 2010 CS105.
Agenda for Class - 03/04/2014 Answer questions about HW#5 and HW#6 Review query syntax. Discuss group functions and summary output with the GROUP BY statement.
Database Programming Sections 6 –Subqueries, Single Row Subqueries, Multiple-row Subqueries, Correlated Subqueries.
1 Welcome! DBT544 students to the iSeries, DB2 Universal Database And SQL interface.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Structured Query Language SQL-II IST 210 Organization of Data IST2101.
For more course tutorials visit CIS 336 All iLabs Week 1 to Week 7 Devry University CIS 336: All iLabs Week 1 to Week 7: Devry University.
BTM 382 Database Management Chapter 8 Advanced SQL Chitu Okoli Associate Professor in Business Technology Management John Molson School of Business, Concordia.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
CSED421 Database Systems Lab View. Page 2  Virtual or logical table which is defined as SELECT query with joins  Act as table but not real data, only.
Using Subqueries to Solve Queries
Using Subqueries to Solve Queries
Agenda: 10/05/2011 and 10/10/2011 Review Access tables, queries, and forms. Review sample forms. Define 5-8 guidelines each about effective form and report.
Using Table Expressions
Structured Query Language
Using Subqueries to Solve Queries
M1G Introduction to Database Development
Using Subqueries to Solve Queries
Using Subqueries to Solve Queries
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

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.

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.

Database for Sample Code in this Presentation 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. 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. 4

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 emp.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!! 6

7 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

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, startwork, hoursworked FROMVEmpTime WHERE lastname = 'Polanski'; 8

Using a view is easy!!! 9 SELECT* FROMvEmpTime WHEREyear(StartWork) = year(getdate()) and month(StartWork) = month(getdate()); SELECTempid, lastname, description, sum(hoursworked) TotalHoursWorked FROMvEmpTime GROUP BYempid, lastname, description ORDER BYlastname

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 – the “shared” column is the same as using a foreign key between tables. 10

Let’s go back to that correlated sub-query from Lab 4 (Thursday before Spring Break) 11 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 ON empOuter.jobtitleID = xjobtitle.jobtitleID WHEREbillingrate > (SELECT AVG(billingrate) FROMxemp empInner WHEREempOuter.jobtitleID = empInner.jobtitleID)

12 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

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

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

Look at the VIEW results and use the VIEW in another query 15 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 the actual job title in the SELECT list?

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

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

Let’s find out which employee worked the most hours in February of the current year 18 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?

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

Use a view to summarize data 20 CREATE VIEW vEmpHours AS SELECT empID, month(startwork) MonthWork, year(startwork) YearWork, sum(minutes/60) TotalHours FROMxtimeworked GROUP BY empid, month(startwork) year(startwork) Look at the result table created by the view: SELECT* FROMvEmpHours

21 Look only at those hours in February of the current year: SELECT* FROMvEmpHours WHEREmonthwork = 2 and yearwork = year(getdate()) Create another view from the view (not necessary, but easier to understand the results): CREATE VIEW vFebHours AS SELECT* FROMvEmpHours WHEREmonthwork = 2 and yearwork = year(getdate())

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

Now add the extra data to make the result table “pretty”, piece at a time SELECTvFeb.empid, firstname + ' ' + lastname "Employee Name", officephone, totalhours FROM vFebHours vFeb LEFT OUTER JOIN xemp emp on vFeb.empid = emp.empid WHERE totalhours = (SELECT MAX(totalhours) from vFebHours)

Finish it up! 24 SELECTvFeb.empid, firstname + ' ' + lastname "Employee Name", officephone, title, totalhours FROM vFebHours vFeb LEFT OUTER JOIN xemp emp ON vFeb.empid = emp.empid LEFT OUTER JOIN xjobtitle jt ON jt.jobtitleid = emp.jobtitleid WHERE totalhours = (SELECT MAX(totalhours) from vFebHours)

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

Time to write a few of your own 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.

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