Using SQL phần 3

Chia sẻ: Tuan Nghia | Ngày: | Loại File: PDF | Số trang:11

0
45
lượt xem
3
download

Using SQL phần 3

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Figure 3.16: Using the DISTINCT keyword to retrieve distinct Country column values As you can see, the SELECT statement only displays Country column values that are unique: duplicate values are eliminated.

Chủ đề:
Lưu

Nội dung Text: Using SQL phần 3

  1. Figure 3.16: Using the DISTINCT keyword to retrieve distinct Country column values As you can see, the SELECT statement only displays Country column values that are unique: duplicate values are eliminated. If you didn't include the DISTINCT keyword, then all the Country column values would be displayed. Combining Retrieved Rows From SELECT Statements You use the UNION operator to combine retrieved rows from SELECT statements into one set of rows. For example, the following SELECT statement uses the UNION operator to combine the retrieved rows from two SELECT statements that retrieve rows from the Products table; the first retrieves rows where the ProductID is less than or equal to 5, and the second retrieves rows where the ProductName starts with Queso: (SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice FROM Products WHERE ProductID
  2. Figure 3.17 shows the results of this statement. Figure 3.17: Using the UNION operator to combine retrieved rows from two SELECT statements Dividing Retrieved Rows into Blocks You use the GROUP BY clause to divide retrieved rows into blocks. You can think of a block as a group of rows that have been condensed into one row. For example, let's say you grouped the SupplierID column of the rows from the Products table. You would get one row for every row that had the same SupplierID column value. The following SELECT statement uses the GROUP BY clause to divide the SupplierID column values into blocks: SELECT SupplierID FROM Products GROUP BY SupplierID; This SELECT statement displays one row for each group of rows that have the same SupplierID column value. You can get the number of rows in each block using the COUNT() function. COUNT() is one of the functions that come built into SQL Server, and is known as an aggregate function because it can operate on more than one row at a time. You use COUNT(*) to get the number of rows, as shown in the following example that retrieves the SupplierID and number of rows for each group of SupplierID column values: SELECT SupplierID, COUNT(*) FROM Products GROUP BY SupplierID;
  3. Figure 3.18 shows the results of this SELECT statement. Figure 3.18: Using the GROUP BY clause to divide rows into blocks You'll learn more about the various SQL Server functions in the next chapter. Restricting Retrieved Groups of Rows You use the HAVING clause to restrict the groups of rows retrieved by the GROUP BY clause. For example, the following SELECT statement uses the HAVING clause to restrict the group of rows returned to those that have more than 4 rows in each group: SELECT SupplierID, COUNT(*) FROM Products GROUP BY SupplierID HAVING COUNT(*) > 4; Figure 3.19 shows the results of this SELECT statement.
  4. Figure 3.19: Using the HAVING clause to restrict retrieved groups of rows Specifying the Display Name for a Column and Aliasing a Table You can use the AS clause to specify the name of a column when it is displayed in the output from a SELECT statement. You might want to do this when you need to display more friendly names or descriptive names for columns. For example, the following SELECT statement uses the AS clause to set the display name of the ProductName column to Product, and the UnitPrice column to Price for each unit: SELECT ProductName AS Product, UnitPrice AS 'Price for each unit' FROM products; Figure 3.20 shows the results of this SELECT statement.
  5. Figure 3.20: Using the AS clause to specify the display name for columns You can also use the AS clause to alias a table. You might want to do this if your table names are long. The following example uses the AS clause to alias the Customers and Orders tables as Cust and Ord respectively: SELECT Cust.CustomerID, CompanyName, Address, OrderID, ShipAddress FROM Customers AS Cust, Orders AS Ord WHERE Cust.CustomerID = Ord.CustomerID AND Cust.CustomerID = 'ALFKI'; Performing Computations Based on Column Values You typically use calculated fields to perform computations based on column values. For example, you might want to use a calculated field to compute the effect of increasing the UnitPrice column of the Products table by 20 percent. The following SELECT statement shows this: SELECT UnitPrice * 1.20 FROM Products WHERE ProductID = 1; This example returns 21.600000. The new unit price is calculated using UnitPrice * 1.20. This is an increase of 20 percent over the current unit price. The next example concatenates the ContactName and ContactTitle columns from the Customers table for the row where the CustomerID equals ALFKI: SELECT ContactName + ', ' + ContactTitle FROM Customers WHERE CustomerID = 'ALFKI';
  6. This example returns Maria Anders, Sales Representative. Retrieving Rows From Multiple Tables So far, you've seen SELECT statements that retrieve rows from only one table at a time. You'll often need to retrieve rows from multiple tables using the same SELECT statement. For example, you might want to see all the orders placed by a customer. To do this, you must specify both the Customers and the Orders tables after the FROM keyword in the SELECT statement and use a table join in the WHERE clause. You must also specify the name of the table when referencing columns of the same name in both tables. The following SELECT statement shows this and retrieves the orders placed by the customer with a CustomerID of ALFKI: SELECT Customers.CustomerID, CompanyName, Address, OrderID, ShipAddress FROM Customers, Orders WHERE Customers.CustomerID = Orders.CustomerID AND Customers.CustomerID = 'ALFKI'; Notice that the Customers and Orders tables are specified after the FROM keyword, and because both tables contain a column named CustomerID, the table name is placed before each reference to the respective column in each table. The table join is done on the CustomerID column of each table (Customers.CustomerID = Orders.CustomerID). Figure 3.21 shows the results of this SELECT statement. Figure 3.21: Using a multitable SELECT statement to retrieve orders placed by a specific customer
  7. The previous SELECT statement used the SQL standard format for joining tables. With SQL Server, you can also use the JOIN keyword for joining tables. The advantage of the JOIN keyword is you can use it to perform outer joins, which you'll learn about shortly. Here's an example that rewrites the previous SELECT statement using the JOIN keyword: SELECT Customers.CustomerID, CompanyName, Address, OrderID, ShipAddress FROM Customers JOIN Orders ON Customers.CustomerID = Orders.CustomerID AND Customers.CustomerID = 'ALFKI'; This SELECT statement returns the same results as the previous example. The disadvantage of the previous two SELECT statements is that they return rows only where the join columns both contain a value, that is, neither column contains a null. This can be a problem if you have rows that have a null value in either of the columns used in the join and you need to actually retrieve those rows. Outer joins solve this problem. There are three types of outer joins: • LEFT OUTER JOIN The LEFT OUTER JOIN (usually shortened to LEFT JOIN) returns all the rows from the table on the left of the join, including those with a column that contains a null value. • RIGHT OUTER JOIN The RIGHT OUTER JOIN (usually shortened to RIGHT JOIN) returns all the rows from the table on the right of the join, including those with a column that contains a null value. • FULL OUTER JOIN The FULL OUTER JOIN (usually shortened to FULL JOIN) returns all the rows from the tables on the left and right of the join, including those with a column that contains a null value. Let's take a look at a couple of examples. First, perform the following INSERT to add a row to the Products table: INSERT INTO Products (ProductName, SupplierID) VALUES ('DVD Player', NULL); Note You'll learn the details of the INSERT statement later in this chapter. You don't need to specify the ProductID column because SQL Server will automatically supply a value using an identity. This identity was established when the Products table was created, and the identity generates a series of values that start with 1 and are incremented by 1 each time it is used. For example, the ProductID column initially contains a series of values from 1 to 77, therefore the next INSERT statement that adds a
  8. row to the Products table will set the ProductID column to 78 for that row-the next identity value. You'll notice that the SupplierID column in the INSERT statement is null. If you now perform the following SELECT statement, you won't see the new row because the SupplierID column of the new row is null and the JOIN won't return that row: SELECT ProductID FROM Products JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID; To see the new row, you use LEFT JOIN in the SELECT statement to retrieve all rows from the table on the left of the join (in this case, the table on the left is the Products table): SELECT ProductID FROM Products LEFT JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID; You can also use LEFT JOIN with IS NULL in the same SELECT statement to retrieve just the new row: SELECT ProductID FROM Products LEFT JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID WHERE Products.SupplierID IS NULL; Retrieving Rows From a View You use a view to retrieve a set of columns from one or more tables. You can think of a view as a more flexible way of examining the rows stored in the tables. For example, one of the views of the Northwind database retrieves an alphabetical list of products, and retrieves the product name and category name, among other columns. This information comes from both the Products and Categories tables. This view is named Alphabetical list of products and the SELECT statement that makes up this view is as follows: SELECT Products.*, Categories.CategoryName FROM Categories INNER JOIN Products ON Categories.CategoryID = Products.CategoryID WHERE (((Products.Discontinued)=0));
  9. You can retrieve all columns and rows from the underlying tables referenced by this view using the following SELECT statement: SELECT * FROM [Alphabetical list of products]; You can also retrieve individual columns from a view. For example, the following SELECT statement retrieves just the ProductName and CategoryName columns from the view: SELECT ProductName, CategoryName FROM [Alphabetical list of products]; Adding a New Row to a Table You use the INSERT statement to add a new row to a table. When adding a new row, you specify the name of the table, the optional column names, and the values for those columns. For example, the following INSERT statement adds a new row to the Customers table: INSERT INTO Customers ( CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax ) VALUES ( 'JPCOM', 'Jason Price Company', 'Jason Price', 'Owner', '1 Main Street', 'New York', NULL, '12345', 'USA', '(800)-555-1212', NULL ); The CustomerID column is the primary key of the Customers table, therefore the new row must contain a unique value for this column. You'll notice that the INSERT statement specifies a null value for the Region and Fax columns (this is specified using the NULL keyword). You can use the Query Analyzer to enter INSERT statements. Figure 3.22 shows the previous INSERT, along with a SELECT statement that retrieves the new row.
  10. Figure 3.22: Using an INSERT statement to add a new row to the Customers table Note You must supply values for all columns that are defined as NOT NULL in a table. Also, the number of columns in the INSERT and VALUES lists must match, and the data type of each column in the INSERT and VALUES lists must also match. When supplying values to all columns in a row, you may omit the column names and just supply the values for each column. For example: INSERT INTO Customers VALUES ( 'CRCOM', 'Cynthia Red Company', 'Cynthia Red', 'Owner', '2 South Street', 'New York', NULL, '12345', 'USA', '(800)-555-1212', NULL ); Modifying Rows in a Table You use the UPDATE statement to update rows in a table. When updating a row, you specify the name of the table, the columns to update, and the new values for the columns. Warning Typically, you should also use a WHERE clause to restrict the rows being updated. If you don't supply a WHERE clause, then all the rows in the specified table will be updated. In many cases, you'll specify the value for the primary key in your WHERE clause. The following UPDATE statement modifies the Address column for the row in the Customers table with a CustomerID of JPCOM: UPDATE Customers SET Address = '3 North Street' WHERE CustomerID = 'JPCOM';
  11. Figure 3.23 shows this UPDATE statement, along with a SELECT statement that retrieves the modified row. Figure 3.23: Using an UPDATE statement to modify the Address column of a row in the Customers table You can use an UPDATE statement to modify multiple columns. For example, the following UPDATE statement modifies the Address and ContactTitle columns: UPDATE Customers SET Address = '5 Liberty Street', ContactTitle = 'CEO' WHERE CustomerID = 'JPCOM';
Đồng bộ tài khoản