20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6<br />

SELECT Category, AVG(DVDPrice)<br />

FROM Films<br />

INNER JOIN Category<br />

ON Films.CategoryId = Category.CategoryId<br />

WHERE AvailableOnDVD = ‘Y’<br />

GROUP BY Category;<br />

The AVG price result receives the alias Average Price, which although not strictly needed, does help<br />

identify what the result means.<br />

Executing this query produces the results in the following table:<br />

Category Average Price<br />

Historical 11.643333<br />

Horror 9.470000<br />

Romance 12.990000<br />

Sci-fi 12.990000<br />

Thriller 7.990000<br />

War 12.990000<br />

MAX() and MIN() in Results<br />

200<br />

The MAX() and MIN() aggregate functions return the lowest and highest values found in a results set,<br />

respectively. Basically, it’s the same as if the results were ordered and the first and last results were<br />

picked from the list. Unlike the SUM() and AVG() functions, you can use MAX() and MIN() with data<br />

types other than numerical data types. For example, you can use MAX() and MIN() to find the earliest<br />

or latest date or time in a date or time field.<br />

The following <strong>SQL</strong> finds the youngest and oldest members in the MemberDetails table:<br />

SELECT MAX(DateOfBirth), MIN(DateOfBirth)<br />

FROM MemberDetails;<br />

It provides the following results:<br />

MAX(DateOfBirth) MIN(DateOfBirth)<br />

1997-05-28 1937-01-20<br />

In addition to a date or time field, you can also choose a character field. Again, the MIN() and MAX() are<br />

the values for the specified column for the first and last records in an ordered results set. For example,<br />

the following <strong>SQL</strong> finds the MIN() and MAX() values for the LastName column in the MemberDetails<br />

table where MemberId is less than 3:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!