cis-linux2.temple.educis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQL…  · Web viewYou...

28
CIS 2109 Second SQL Server Lab SQL Queries (SELECT statements) CONTENTS 1. Objectives...................................................................2 2. Introduction.................................................................2 2.1 Logging In...............................................................2 2.2 Pre-requisites...........................................................2 3. General Syntax of a SQL Query (SELECT Statement)............................3 4. Select Columns, Rename Columns..............................................3 5. Calculations on Columns (SQL Functions, Concatenation Operator).............4 6. Help with SQL...............................................................5 6. Query Selection (WHERE Clause, Comparison Operators)........................5 7. Sorting Results (ORDER BY Clause)...........................................7 8. Joining Data from More than One Table (INNER JOIN)..........................8 8. Joining Data using OUTER JOIN..............................................10 9. Using Distinct..............................................................13 10. Aggregate Functions.......................................................13 11. Grouping Results (GROUP BY Clause)........................................15 12. Selecting Groups (HAVING Clause)...........................................16 13. Sub-queries...............................................................16 14. Correlated Subqueries......................................................18 16. Homework Submission........................................................19 1

Transcript of cis-linux2.temple.educis-linux2.temple.edu/~sallyk/tutorials_SQL_Server/SQL…  · Web viewYou...

CIS 2109 Second SQL Server LabSQL Queries (SELECT statements)

CONTENTS

1. Objectives........................................................................................................................................................................2

2. Introduction.....................................................................................................................................................................2

2.1  Logging In.................................................................................................................................................................2

2.2  Pre-requisites...........................................................................................................................................................2

3.  General Syntax of a SQL Query (SELECT Statement)..................................................................................................3

4.  Select Columns, Rename Columns.................................................................................................................................3

5.  Calculations on Columns (SQL Functions, Concatenation Operator).............................................................................4

6.  Help with SQL...............................................................................................................................................................5

6.  Query Selection (WHERE Clause, Comparison Operators)...........................................................................................5

7.  Sorting Results (ORDER BY Clause)............................................................................................................................7

8.  Joining Data from More than One Table (INNER JOIN)...............................................................................................8

8.  Joining Data using OUTER JOIN................................................................................................................................10

9. Using Distinct................................................................................................................................................................13

10.  Aggregate Functions...................................................................................................................................................13

11.  Grouping Results (GROUP BY Clause).....................................................................................................................15

12. Selecting Groups (HAVING Clause)...........................................................................................................................16

13.  Sub-queries.................................................................................................................................................................16

14. Correlated Subqueries.................................................................................................................................................18

16. Homework Submission...............................................................................................................................................19

1

1. OBJECTIVES

In this lab, you will create queries to retrieve data from a SQL Server Database. You will use the following features of the SQL language.

Selecting columns of data from a table (SELECT … FROM …) to return a result set. Filtering rows of the result set by applying certain criteria (WHERE) with comparison operators (e.g., >,

=, LIKE)  Using functions, e.g., GETDATE( ), CONVERT( ) to transform columns in the result set Renaming columns in the result set Sort rows in the result set (ORDER BY) Grouping data and using aggregate functions on resulting groups (e.g., sum, min, max, average) Joining data from more than one table Using Sub-queries and Correlated queries

 

2. INTRODUCTION 

In this lab you will continue working with the Microsoft SQL Server database.  You will use the SQL language to compose queries that ask practical questions of the manufacturing database.  Thus, it is very    important that you understand the database schema as it affects the construction of the commands.  Your results should match the answers given in this lab.  If you get something different, verify that you entered the correct command and then ask for help from the lab assistant.  You are encouraged to explore your own queries and exercise additional options. 

2.1  LOGGING IN 

Recall that to start MS Sql Server, you click:

     Start - All Programs - Microsoft SQL Server 2005 - SQL Server Mgt Studio

Your database is stored on a server named DWARF. Your username is in this format fa08_c2109xxxx and your assigned password is the last four digits your username. Review the previous Lab if you are having trouble starting Microsoft SQL Server, 'Query Analyzer', 'Enterprise Manager', or connecting to your database.

2.2  PRE-REQUISITES 

This lab requires that you have completed the previous lab, which means your database must be fully loaded with the tables, relationships, and data of the sample manufacturing database. In particular, we will use the following tables: Customer_t, Order_t, Order_Line_t and Producct_t. If you do not have the manufacturing database loaded, go to the last step of the previous lab and load that database now.

2

3.  GENERAL SYNTAX OF A SQL QUERY (SELECT STATEMENT)

In SQL, a query is a (syntactically correct) expression of a question that we want to ask of a database. The SQL command that we use to compose a query is called a SELECT statement. When we execute a query (or SELECT statement) against a database, we get what is called a “result set”. The result set is a relation (rows and columns of data) that answer the query.

The general syntax of the SQL SELECT statement is shown below:

SELECT [ALL / DISTINCT [column_list        FROM table_list       [WHERE conditional expression]       [GROUP BY group_by_column_list]       [HAVING conditional expression]       [ORDER BY order_by_column_list];

Notation: Square brackets [ ] indicate that what is inside is optional. The slash indicates that you can select one or the other (e.g., ALL or DISTINCT).

The basic SQL SELECT statement lets you specify which columns (the column_list) you want to see , which rows you want to see (the WHERE clause), and which order you want to see them in (the ORDER BY clause). Note: GROUP BY and HAVING clauses will be introduced later in this lab.

In this lab, you will use many variations of the SELECT command to query your database.  

4.  SELECT COLUMNS, RENAME COLUMNS

In a simple query, you specify the columns that you want to see from a particular table. In the example below, the “column_list” is employee_ID, employee_name. The “table_list” is the single table customer_t. Because there is no “WHERE” clause, all rows of data in the table will be returned in the result set.

SELECT employee_ID, employee_name FROM customer_t;

If you want to see all the columns of a table (perhaps you don’t know the column names), you can use the * which acts as a “wild card” returning all columns like this:

SELECT * FROM customer_t;

You can also rename the column names (perhaps to make them user friendly) using the “AS” keyword as shown. If you want the result set column names to have spaces in them, use the square brackets (to delineate the column name):

SELECT employee_ID AS Employee_Number, employee_name AS [Employee Name]FROM customer_t;

3

5.  CALCULATIONS ON COLUMNS (SQL FUNCTIONS, CONCATENATION OPERATOR)

You can also apply functions on the returned columns. For example, if you wanted to find the number of days since each order was placed, you could use the GETDATE( ) function (to return today's date) and the DATEDIFF function to calculate the number of days between today and the order date.

Note the following aspects of the SQL SELECT statement below:

the CONVERT function formatted a date to an 8 character date (to exclude the minutes and seconds) the converted date column was renamed to “Order Date” the DATEDIFF function calculated the number of days between today (GETDATE( )) & the order date.

Concatenation means putting two character strings together to form one character string. The SQL concatenation operator is +.  Note that if you want to concatenate a numeric value (with anything), you must first convert the number to a character string. In the example below, you concatenate city, state, and zip code (converted to character string) to make up an address.

       SELECT Customer_name AS Name,                           City + ', ' + state + ' ' + CONVERT(char, Postal_Code) AS Address        FROM customer_t

 Exercise: Run the above SELECT statement without the CONVERT to see what kind of error you get.

4

6.  HELP WITH SQL

To find out about more SQL functions, you can check the help function of SQL Server or check the W3Schools website http://www.w3schools.com/sql/sql_functions.asp. Note that there is “ANSI standard” SQL (which all database vendors should implement) and there is proprietary extensions to the SQL language (this means parts of the language that are only implemented by that particular DBMS vendor). Although proprietary extensions to the language may be desirable, you should avoid their usage to prepare for the possibility that your software may some day be migrated to another database platform (e.g., SQL server, oracle, etc).

Exercise: Use the HELP system to verify the use of the CONVERT function (and see what other conversions can be done). Check the W3 schools website and compare its SQL help with MS SQL Server’s help. http://www.w3schools.com/sql

6.  QUERY SELECTION (WHERE CLAUSE, COMPARISON OPERATORS)

To restrict the rows of your result set, you can add the WHERE clause as shown below. The following SELECT statement will only return the rows where the unit_price is greater than 300. Because unit_price was defined as a NUMERIC TYPE field, you do NOT use quotations around the literal value (300).

SELECT product_name, product_finish, unit_price    FROM product_t        WHERE unit_price < 300;

You need to pay attention to the data type of the columns that are part of your WHERE clause. If a zip code was specified as numeric, you should not include quotes around the values (e.g., WHERE ZIP_CODE=19406), but if ZIP_CODE was specified as a CHARACTER TYPE, your WHERE clause should include single quotes around the literal values (e.g., WHERE ZIP_CODE='19406').

When selecting character values, you need to be careful about SPACES. While you can’t see them, they may (or may not) be there. For example, 'SALLY' and 'SALLY ' are not the same. Blank (' ') is not the same as ' ' (empty string) which is not the same as NULL (no data). You can use functions that TRIM leading and/or trailing spaces and/or you can use a LENGTH function to see why you may not be getting the data you expect.

When a column contains NULL, you may find unexpected results when you use that column in a WHERE clause. For example, the following SELECT statement (which we saw before) might not bring back rows where there is no unit_price. See if you can come up with some SELECT statements that prove or disprove this.

SELECT product_name, product_finish, unit_price    FROM product_t        WHERE unit_price < 300;

If you want to select based on a date type field, you need to know what delimiter to put around the date literal and this does seem to vary between one DBMS vendor and another. The following SELECT statement would work in MS Access because Access uses square brackets to delimit date literal values. Does this statement work in MS SQL?

SELECT order_id FROM order_t WHERE order_date = [1998-10-21];

5

If that statement does not work, perhaps you could convert the date value to a character string and select on that…

SELECT order_id FROM order_t WHERE CONVERT(char(8), order_date) = ‘10/21/98’;

Search for SQL help and try to find out what date delimiter MS SQL uses.

In addition to the usual comparison operators (>, <, >=, <=. = <>), there are a couple of other operators, such as BETWEEN and IN.

Examples:The IN operator: WHERE customer_state IN ('PA', 'NJ', 'DE')The IN operator: WHERE customer_state NOT IN ('PA', 'NJ', 'DE')The Between Operator: WHERE zip_code    BETWEEN 19400 AND 19500

There are also some Wild Card symbols that can be very useful when searching for character values.

Wild card symbols:    %    Matches any string of zero or more characters    _     Matches any single character    [ ]    Matches a single character listed within brackets.    [ - ]    Matches a single character within the given range    [ ^ ] Matches a single character not listed after the caret   

Examples:   Customer_state LIKE N[A-J]                 will include  'NC' and 'NJ' but not 'NY'   Customer_name LIKE 'DAMI[EO]N'     will include 'Damien' and 'Damion'   Zip_code  NOT LIKE [1-9]%                  will include '02107' and '08123'

Question:  In California, what Customer Names start with ‘C’?

SQL Query:  SELECT customer_name        FROM customer_t             WHERE customer_name LIKE 'C%' AND state = 'CA';

Result Set:

Customer_name                -----------------------------------California Classics                 

6

Question:    List product name, finish and unit price for all products with 'Desk' or 'Table' in the product description with price over $300 

SQL Query:  SELECT product_name, product_finish, unit_price    FROM product_t        WHERE (product_name LIKE '%Desk'                OR product_name LIKE '%Table')                AND unit_price > 300 ;

Result Set:Product_name Product_Finish         Unit_price------------------------------------------------------------------------------------Computer Desk Natural Ash          375Writer's Desk  Cherry               3258-Drawer Desk White Ash           750Dining Table   Natural Ash         800

7.  SORTING RESULTS (ORDER BY CLAUSE)

Question:   List customer, city and state for all customers  whose address is  Florida, Texas, California or Hawaii.  List the customers alphabetically by state, and alphabetically by customer name within each state.

SQL Query:  SELECT state, customer_name, city, state    FROM customer_t        WHERE state IN ('FL', 'TX', 'CA', 'HI')ORDER BY state, customer_name

Result:ST Customer_name           City                            --------------------------------------------------------------------CA California Classics      Santa Clara               CA Impressions               Sacramento              FL Contemporary Casuals    Gainsville                   FL M and H Casual Furniture    Clearwater                 FL Seminole Interiors               Seminole                   HI Kaneohe Homes              Kaneohe                    TX Value Furniture                  Plano                         

Note:  all customers from each state are grouped together, and within each state, customer names are alphabetized.  The sorting order is determined by the order in which the columns are listed in the ORDER BY clause.

To sort the output in descending order, enter the keyword DESC after the sorted column. ASC (the default) means ascending order.

7

SELECT customer_name AS Name, city + ', ' + state AS Address    FROM customer_tORDER BY state DESC, customer_name ASC

Remember never to name tables or columns using SQL keywords. DESC is one of those keywords that you are often tempted to use (e.g., as an abbreviation for Description). Remember to avoid this !

Note, you can also sort by a column alias or an expression. However, sorting a large table on an expression that does not have an index (for that exact expression) will probably result in a performance problem.

8.  JOINING DATA FROM MORE THAN ONE TABLE (INNER JOIN)

As you can imagine in a relational database, queries often need to join data from two or more tables. The implicit (implied) syntax for an Inner Join is:

    SELECT column_list    FROM table_1, table_2 [,table_3] ......    WHERE table_1.column_name = table_2.column_name                [AND table_2.column_name = table_3.column_name] .....

Example SQL Query using WHERE clause to join data from two tables:

        SELECT customer_t.customer_id, customer_t.customer_name, Order_id        FROM customer_t, order_t        WHERE customer_t.customer_id = order_t.customer_id

AND customer_name LIKE ‘C%’;

Customer_id   customer_name                   Order_id------------------------------------------------------------------------1                     Contemporary Casuals     10018                     California Classics           10021                    Contemporary Casuals     1010

Note that when your query includes data from two or more tables, there usually are field names common to both tables. In this case, you must prefix the column name with the table name (or table alias) in order to unambiguously specify a particular column. Because order_id was only in table order_t, it was not mandatory to precede order_id with its table name (order_t.order_id).

In order to save some typing, it is not unusual to alias the table names. In the example below, table customer_t is aliased as C and order_t is aliased as O. This SQL Query yields the same results as the previous example.

Example SQL Query using table aliases:

        SELECT C.customer_id, customer_name, Order_id        FROM customer_t AS C, order_t AS O        WHERE C.customer_id = O.customer_id

8

AND customer_name LIKE ‘C%’;

If your query uses two instances of the same table, you MUST use table alias names. For example, suppose you had an Employee table with a “boss” link back to the Employee table. If you wanted to provide a list of everyone’s boss, you’d write a query like this:

        SELECT Worker.emp_id, Worker.name, Boss.emp_id, Boss.name        FROM Employee AS Worker, Employee AS Boss        WHERE Worker.Boss_id = Boss.Emp_id

Using table and column aliases, create a query (from your manufacturing database), that yields these results. (You will be using the employee_t table and fields employee_id, employee_name, and supervisor_id).

Boss_ID Boss_Name Employee_ID Employee_name

1Paquette 2 Johnson

1Paquette 3Delgado

5Braak 4Bradish

5Braak 7Tate

5Braak 8Van Horn

5Braak 9Moore

6 Shuster 1Paquette

6Shuster 5Braak

In the SQL-92 standard, a new syntax was introduced – to differentiate join conditions from other conditions. This syntax is:

SELECT column_listFROM table1

INNER JOIN table2 ON table1.column_name=table2.column_name

So, the following two SQL statements are functionally equivalent – they return the same result set. The second syntax is preferred, however, since it does differentiate join conditions from other conditions and thus the SQL statement is easier to read. Also, it is possible that some DBMS software is better able to double check (provide error or warning messages) if you specify a join condition where a foreign key relationship does not exist.

Joining data using WHERE clause(old SQL syntax)

Joining data using JOIN ... ON(new, preferred SQL syntax)

9

SELECT customer_t.customer_id, customer_name, Order_id FROM customer_t, order_t     WHERE customer_t.customer_id = order_t.customer_id;

SELECT customer_t.Customer_id, customer_name, Order_id FROM customer_t JOIN  order_t     ON

customer_t.customer_id = order_t.customer_id;

8.  JOINING DATA USING OUTER JOIN

All of the preceding join examples have been INNER JOINs. This means that the result set only includes a row if it has a foreign key value that points to a row in the second table. If you use an OUTER JOIN, then the row will be included even if the foreign key value is empty. If the foreign key is a required field, then an INNER JOIN and an OUTER JOIN (on that field) return the same results (because all fields will have values).

When a foreign key field is optional (as in Salesman_t.Territory_Id) and some of these values are null, then there will be difference (in the number of rows returned) between an INNER JOIN and an OUTER JOIN. To demonstrate this, I deleted the Territory_ID for Salesman #8 (and the DBMS let me do this because Salesman_t.Territory_ID was specified as optional field). In the left part of the diagram below, you see that table Salesman_t has 12 salesmen, but only 11 of these are assigned to a territory. In the right part of the diagram (where Salesman_t is INNER JOINed with Territory_t), you see that the query only returns the 11 salesmen that do have a specified territory.

SalesPerson_tTable

Query: Inner Join between SalesPerson_t & Sales_Territory_t

10

INNER JOIN: SELECT Salesperson_t.Salesperson_ID, Salesperson_t.Salesperson_name, Salesperson_t.Territory_ID, Sales_territory_t.[Territory description]

FROM Sales_territory_t INNER JOIN Salesperson_t ON Sales_territory_t.Territory_ID = Salesperson_t.Territory_ID;

The SQL query below (see SQL Code beneath the table) uses an OUTER JOIN. It returns ALL rows in the RIGHT table (SalesPerson_t), even if a row in that table does NOT reference a Territory_ID.

Salesperson_ID Salesperson_name Territory_ID Territory description

1 Johnson 1Northwest

2Haverty 1Northwest

11

Salesperson_ID

Salesperson_name

Territory_ID

1 Johnson 1

2Haverty 1

3Rodriguez 2

4Chan 2

5Swensen 3

6Kotlowski 3

7Beauclair 4

8Overstreet

9Rader 5

10Himenez 5

11O'Neill 6

12Majeska 6

Salesperson_ID

Salesperson_name Territory_ID Territory

description

1 Johnson 1Northwest

2Haverty 1Northwest

3Rodriguez 2 Southwest

4Chan 2Southwest

5 Swensen 3Midwest

6Kotlowski 3Midwest

7Beauclair 4 South

9Rader 5 Intermountain

10Himenez 5 Intermountain

11O'Neill 6Northeast

12Majeska 6Northeast

Salesperson_ID Salesperson_name Territory_ID Territory description

3Rodriguez 2 Southwest

4Chan 2Southwest

5 Swensen 3Midwest

6Kotlowski 3Midwest

7Beauclair 4 South

8Overstreet

9Rader 5 Intermountain

10Himenez 5 Intermountain

11O'Neill 6Northeast

12Majeska 6Northeast

OUTER JOIN: SELECT Salesperson_t.Salesperson_ID, Salesperson_t.Salesperson_name, Salesperson_t.Territory_ID, Sales_territory_t.[Territory description]

FROM Sales_territory_t RIGHT JOIN Salesperson_t ON Sales_territory_t.Territory_ID = Salesperson_t.Territory_ID;

 

12

Here is another example using the OUTER JOIN.

Question:   Display the names of all customers with their orders. Include all customers whether they placed orders or not.

         

Note that all customer names were returned whether or not they had placed an order.  A NULL is displayed where the order doesn't exist. 

13

9. USING DISTINCT 

SQL can also provide a list of distinct values (i.e., no repetition), as shown below.

SELECT order_idFROM order_line_t;

SELECT  DISTINCT  order_idFROM order_line_t;

Order_id----------100110011001100210031004100410051006100610061007100710081008100910091010

Order_id----------1001100210031004100510061007100810091010

10.  AGGREGATE FUNCTIONS

SQL provides aggregate (group) functions like, SUM, AVG, MAX and MIN. To learn about additional SQL aggregate functions, use the HELP system. 

Question:    How many line items  were ordered on order 1004?

SQL Query:   SELECT COUNT  (*)    AS  order_count FROM order_line_tWHERE order_id = 1004 ;

Result:             2

This does not use any aggregate functions (but we’ll work up to an aggregate function in the next example)…

14

Question:    For order number 1004, what product was ordered, how many were ordered, what was the unit price, and what amount of money was spent per product?

SQL Query:   SELECT Order_line_t.Order_ID, Order_line_t.Product_ID, Product_t.Product_Name, Order_line_t.Quantity, Product_t.Unit_Price, [quantity]*[unit_price] AS amount

FROM Product_t INNER JOIN Order_line_t ON Product_t.Product_ID = Order_line_t.Product_ID

WHERE Order_line_t.Order_ID=1004;

Result:           

Order_ID Product_ID Product_Name Quantity Unit_Price amount

1004 8Computer Desk 2 $250.00 $500.00

1004 68-Drawer Desk 2 $750.00 $1,500.00

Question:    What amount of money was spent on order 1004?

SQL Query:   SELECT SUM ([quantity]*[unit_price]) AS amount

FROM Product_t INNER JOIN Order_line_t ON Product_t.Product_ID = Order_line_t.Product_ID

WHERE Order_line_t.Order_ID=1004;

Result:           

amount

$2,000.00

15

11.  GROUPING RESULTS (GROUP BY CLAUSE)

GROUP BY divides the table into subsets (by groups);  then an aggregate function can be used to  provide summary information for that group.

Question:   Count the number of customers with addresses in each state.

SQL Query:   SELECT state, COUNT (state) as Customers_In_State     FROM customer_t        GROUP BY state;

Result:            ST     Customers_In_State-- ---------------------CA           2CO           1FL            3HI             1MI             1NJ             2NY             1PA            1TX             1UT             1WA            1

Question:    What amount of money was spent on each order?

SQL Query:   SELECT Order_ID, SUM ([quantity]*[unit_price]) AS amount

FROM Product_t INNER JOIN Order_line_t ON Product_t.Product_ID = Order_line_t.Product_ID

GROUP BY Order_ID;

Result:          

Order_ID amount

… …

1002 $1,875.00

1003 $1,125.00

16

Order_ID amount

1004 $2,000.00

… …

 12. SELECTING GROUPS (HAVING CLAUSE)

The WHERE clause tells which rows should be included. The HAVING clause tells which groups should be included. 

Question:   Find only states with more than one customer.

SQL Query:SELECT state,  COUNT (state)    FROM  customer_t        GROUP BY STATE            HAVING COUNT(state) > 1;

Result:ST     COUNT(state)-- --------------------CA         2 FL         3 NJ         2

 

13.  SUB-QUERIES 

A sub-query is a SELECT statement within another SELECT statement.  It enables you to build queries that would be difficult or impossible to do otherwise. A sub-query can be included in the:

WHERE clause as a search condition SELECT clause as a column specification HAVING clause as a search condition FROM clause as a table specification, or

These facts can help you understand how and where to use sub-queries: When a sub-query returns a single value, it can be used anywhere you would normally use an

expression. When a sub-query returns a single-column result set with two or more rows, it can be used in place of a

list of values, such as the list for the IN operator. A sub-query doesn't typically include the GROUP BY or HAVING or ORDER BY clauses. A sub-query can be nested within another sub-query, although this can become difficult to read.

17

In the following example, the sub-query returns a single value which is used in the WHERE clause (where you might have used a literal or any other simple expression).

Question:  What's the name of the customer who placed the last (highest numbered) order?

SQL Query:

SELECT customer_name FROM customer_t, order_t WHERE customer_t.customer_id=order_t.customer_id

AND order_t.order_id = (SELECT max(order_id) FROM order_t);

Result of Sub-query (the order with highest order number): 1010

Result of Query (the customer who placed order number 1010):customer_name                -----------------------------   Value Furniture       

In this example, the sub-query returns a single column result set which is used as the list for the IN operator.

Question: Display the name of all customers who placed orders.

SQL Query: SELECT customer_name    FROM customer_t        WHERE customer_ID IN                       (SELECT DISTINCT customer_ID                             FROM order_t);

Result:customer_name-------------------------------Contemporary CasualsValue FurnitureHome FurnishingsEastern FurnitureImpressionsCalifornia ClassicsAmerican Euro LifestylesBattle Creek FurnitureMountain Scenes

 

18

14. CORRELATED SUBQUERIES 

In the sub-queries discusses above, the sub-query is executed once for the entire query. If a sub-query is executed once for each row that's processes by the outer query, that sub-query is called a correlated sub-query.

A correlated subquery refers to a value that's provided by a column in the outer query. Because that value varies depending on the row that's being processed, each execution of the subquery return a different result.

To refer to a value in the outer query, a correlated subquery uses a qualified column name that includes the table name from the outer query. If the subquery uses the same table as the outer query, an alias must be assigned to the one of the tables to remove ambiguity. 

 Question: For the raw materials, list their  ID, description and price and the vendor _ID supplying the raw material. Only display  the material that costs more than the average price of all materials with the same name.

(Recall that a particular raw material can be purchased from different vendors at various prices. Note that for every material ID in the outer query (e.g., from the table aliased as raw_outer), the sub-query finds the average price for that raw material – as priced by various vendors.

 SQL Query:SELECT Material_ID, Grade, Unit_price, Material_Description

FROM Raw_materials_t AS raw_outerWHERE unit_Price >    (SELECT AVG(unit_price)     FROM Raw_Materials_t AS raw_sub     WHERE raw_outer.Material_Description = Raw_sub.Material_Description);

The SQL and results in the Query Analyzer are:

19

Question:  Select the employees with salary greater than the average salary of the employees working for same supervisor.

   16. HOMEWORK SUBMISSION Copy the following questions (A-H) into a Word document. For each question, enter the SQL select statement into the Query Analyzer, run it, then copy/paste the Query Analyzer screen into the word document (after the question it’s answering). For each query, make sure to label every item (for example, do not just provide customer number, also provide customer name). When you are done, attach the word document to blackboard assignment.A. List the skills of each employee ordered alphabetically first by employee name and then by skill name. Alias

each table and each column name. Use an INNER JOIN.B. How many skills does each employee have?C. For each Vendor offering of Material, show the Material (ID, description, and grade), the price, and the

Vendor that offers it. Sort by material ID, then descending by price (highest price first). Make sure each Material would be included even if is no vendor offers that material (hint: must use OUTER JOIN).

D. For each work center, list the highest and lowest paid employees and tell what their salaries are. (Your answer should be in a single query with one row per work center..)

E. For each Material, show the Vendor who offers that material for the lowest price and what that price is.F. For each Product, show which customer ordered the most. Show the product name, customer name,

quantity ordered, and how much that cost (based on product’s unit price and quantity).G. For each Work Center, show the maximum salary. Give the maximum salary column an alias “max_sal”.H. For each Work Center, show the name(s) of the employee(s) who make the maximum salary. (It’s possible

that more than one person might make the highest salary within a work center.) Hint, put parentheses around your query from the previous question and then follow that with a table/query alias, e.g., MAX_SAL_QUERY (as shown below). You can use this parenthesized select statement just like you could use any table in a query. Then join the Employee table with this MAX_SAL_QUERY (matching on the high salary).

SELECT MAX_SAL_QUERY.Work_Center_ID, MAX_SAL_QUERY.Location ,employee_id, employee_name, MAX_SAL_QUERY.max_sal

FROM employee_t INNER JOIN ( SELECT …Max(Salary) as max_sal FROM … ) AS MAX_SAL_QUERYON employee_t.salary = MAX_SAL_QUERY.max_sal;

20