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.

Running the query, complete with a WHERE clause, produces the following final results:<br />

State<br />

Golden State<br />

Mega State<br />

New State<br />

The GROUP BY clause isn’t limited to just one column; it can be two or more as the following query shows:<br />

SELECT City, State<br />

FROM MemberDetails<br />

WHERE State IN (‘Mega State’, ‘Golden State’,’New State’)<br />

GROUP BY City, State;<br />

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

City State<br />

Big City Mega State<br />

Dover Golden State<br />

New Town New State<br />

Orange Town New State<br />

Townsville Mega State<br />

Windy Village Golden State<br />

The order of the columns in the GROUP BY clause affects the order of results, but it doesn’t change the<br />

results as a whole, just the order in which they arrive.<br />

Both examples include the same columns in the SELECT results set, as in the GROUP BY clause, and this is<br />

no accident. Most DBMSs don’t allow the columns that appear in the results to differ from the columns<br />

in the GROUP BY clause. The reason for this is that if you specify no group for a column in the SELECT<br />

statement, then the DBMS has no way of deciding which value to include for a particular group.<br />

Remember, your results can include only one identical record per group; each row represents the results<br />

from a group of records and not the individual records themselves. You can’t include an ungrouped column;<br />

otherwise there may be more than one row for each group, which isn’t allowed.<br />

Summarizing and Aggregating Data<br />

Grouping and Aggregating Data<br />

Until now, results obtained from the database have all consisted of a set of individual records rather than<br />

records that have been summarized by, say, including an average or counting records. Queries have<br />

answered questions such as “Who are the members of the film club and which state do they live in?”<br />

191

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

Saved successfully!

Ooh no, something went wrong!