Você está na página 1de 26

Sorting Query Results

Like the rows of a table in the database, the rows of query results are not arranged in any particular order. You can ask SQL to sort the results of a query by including the ORDER BY clause in the SELECT statement. You can request sorting in an ascending or descending sequence, and you can sort on any item in the select list of the query. By default, SQL sorts data in ascending sequence.(Keyword Used : ASC) To request sorting in descending sequence, the keyword DESC is included in the sort specification

ORDER BY clause syntax diagram


ORDER BY column-name column-number ,

ASC DESC

Show the sales for each office, sorted in alphabetical order by region, and within each region by city. SELECT city, region, sales FROM Offices ORDER BY region, city
CITY REGION -----------------Atlanta Eastern Chicago Eastern New York Eastern Denver Western Los Angeles Western SALES ----------367911.00 735042.00 692637.00 186042.00 835915.00

region :Major sort key , city : Minor sort key (used as "tie breakers)

List the offices, sorted in descending order by sales, so that the offices with the largest sales appear first.
SELECT city, region, sales FROM Offices ORDER BY sales DESC
CITY REGION -----------------Los Angeles Western Chicago Eastern New York Eastern Atlanta Eastern Denver Western SALES ----------835915.00 735042.00 692637.00 367911.00 186042.00

If the column of query results to be used for sorting is a calculated column, it has no column name to be used in a sort specification. You must specify a column number instead of a column name List the offices, sorted in descending order by sales performance, so that the offices with the best performance appear first.
SELECT city, region, (sales - target) FROM Offices ORDER BY 3 DESC
CITY REGION --------------------New York Eastern Los Angeles Western Atlanta Eastern Chicago Eastern Denver Western (SALES-TARGET) ----------117637.00 110915.00 17911.00 64958.00 113958.00

The SQL2 standard allows you to control the sorting order used by the DBMS for each sort key. List the offices, sorted in alphabetical order by region, and within each region in descending order by sales performance.
SELECT city, region, (sales - target) FROM Offices ORDER BY region ASC, 3 DESC
CITY REGION ----------- ----------New York Eastern Atlanta Eastern Chicago Eastern Los Angeles Western Denver Western (SALES-TARGET) ----------117,637.00 17,911.00 64,958.00 110,915.00 113,958.00

Column/Aggregate Functions
SQL lets you summarize data from the database through a set of column/aggregate functions.
A SQL column function takes an entire column of data as its argument and produces a single data item that summarizes the column.

Computing a Column Total (SUM)


The SUM() column function computes the sum of data values of a column. The data in the column must have a numeric type (integer, decimal, floating point). The result of the SUM() function has the same basic data type as the data in the column, but the result may have a higher precision. For example, if you apply the SUM() function to a column of 16-bit integers, it may produce a 32-bit integer as its result.

What are the total quotas and sales for all salespeople?
SELECT SUM(quota), SUM(sales) FROM SALESREPS
SUM(QUOTA) -------------2700000.00 SUM(SALES) ------------2893532.00

Computing a Column Average (AVG)


The AVG() column function computes the average of data values of a column. The data in the column must have a numeric type. Its result may have a different data type than that of the values in the column.

Calculate the average price of products from manufacturer ACI.


SELECT AVG(price) FROM Products WHERE mfr_id = 'ACI
AVG(PRICE) ----------804.29

Finding Extreme Values (MIN and MAX)


The MIN() and MAX() column functions find the smallest and largest values in a column respectively. The data in the column can contain numeric, string, or date/time information. The result of the MIN() or MAX() function has exactly the same data type as the data in the column.

What are the smallest and largest assigned quotas?


SELECT MIN(QUOTA), MAX(QUOTA) FROM SALESREPS
MIN(QUOTA) -----------200000.00 MAX(QUOTA) ----------350000.00

What is the earliest order date in the database?


SELECT MIN(ORDER_DATE) FROM ORDERS
MIN(ORDER_DATE) --------------04-JAN-89

When using MIN() and MAX() with string data, the comparison of two strings depends upon the character set being used. ASCII character set
digits uppercase characters lowercase characters

EBCDIC character set


lowercase characters uppercase characters digits

The COUNT() column function counts the number of data values in a column. The data in the column can be of any type. The COUNT() function always returns an integer, regardless of the data type of the column. How many customers are there?
SELECT COUNT(cust_num) FROM CUSTOMERS
COUNT(CUST_NUM) ---------------21

Counting Data Values (COUNT)

SQL supports a special COUNT(*) column function, which counts rows rather than data values. How many orders for more than Rs. 25,000 ?
SELECT COUNT(*) FROM Orders WHERE amount > 25000.00
COUNT(*) --------4

NULL Values and Column Functions


The SUM(), AVG(), MIN(), MAX(), and COUNT() column functions ignore the NULL values except COUNT(*)

Rules for handling NULL values in column functions:


If any of the data values in a column are NULL, they are ignored for the purpose of computing the column function's value. If every data item in the column is NULL, then the SUM(), AVG(), MIN(), and MAX() column functions return a NULL value; the COUNT() function returns a value of zero.

The COUNT(*) counts rows and does not depend on the presence or absence of NULL values in a column. If there are no rows, it returns a value of zero.

Duplicate Row Elimination (DISTINCT)


You can specify the DISTINCT keyword at the beginning of the select list to eliminate duplicate rows of query results. To eliminate duplicate values, the keyword DISTINCT is included before the column function argument, immediately after the opening parenthesis. How many different vendors are currently represented in the PRODUCT table?
SELECT COUNT(DISTINCT V_Code) FROM Product
COUNT(DISTINCT V_Code) ------------------------------------3

Grouped Queries (GROUP BY Clause)


The GROUP BY clause of the SELECT statement provides the capability to summarize query results at a "subtotal" level. What is the average order size?
SELECT AVG(salary) FROM emp1
AVG(salary) -----------8256.37

What is the average salary for each department?


SELECT dep_no, AVG(salary) FROM emp1

GROUP BY dep_no
dep_no ---10 20 30 AVG(salary) ----------8,876.00 5,694.00 1350.00

Group Search Conditions (HAVING Clause)


The WHERE clause can be used to select and reject the individual rows that participate in a query. The HAVING clause can be used to select and reject row groups. The HAVING clause specifies a search condition for groups.

What is the maximum salary of department 20?


select dep_no,max(salary) from emp1 group by dep_no having dep_no=20; DEP_NO -----20 MAX(SALARY) ----------80000

Date functions
ADD_MONTHS(d,n): Where d: date & n: no of months Returns date after adding the no of months specified in the function SQL> select add_months(sysdate,4) from dual; ADD_MONTH --------29-NOV-11

LAST_DAY(date):
Returns last date of the month specified with the function. SQL> select last_day(sysdate) from dual; LAST_DAY( --------31-JUL-11 SQL> select last_day('01-jan-82') from dual; LAST_DAY( --------31-JAN-82

SQL> select months_between('01-jan-82','01jan-83') from dual; MONTHS_BETWEEN('01-JAN-82','01-JAN-83') ---------------------------------------12 SQL> select months_between('01-jan-83','01jan-82') from dual; MONTHS_BETWEEN('01-JAN-83','01-JAN-82') --------------------------------------12

MONTHS_BETWEEN(D1,D2): Returns number of months between D1 & D2.

Você também pode gostar