29.01.2014 Views

Introduction to Database Systems Queries in SQL The select ...

Introduction to Database Systems Queries in SQL The select ...

Introduction to Database Systems Queries in SQL The select ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Group<strong>in</strong>g and Target List<br />

In a query that has a group by clause, only such attributes can appear<br />

<strong>in</strong> the target list (except for aggregation functions) the appear <strong>in</strong> the<br />

group by clause.<br />

Example: Incorrect: <strong>in</strong>come of persons, grouped accord<strong>in</strong>g <strong>to</strong> age<br />

<strong>select</strong> age, <strong>in</strong>come<br />

from person<br />

group by age<br />

<strong>The</strong>re could exist several values for the same group.<br />

Correct: average <strong>in</strong>come of persons, grouped by age.<br />

<strong>select</strong> age, avg(<strong>in</strong>come)<br />

from person<br />

group by age<br />

55<br />

Group<strong>in</strong>g and Target List (cntd)<br />

<strong>The</strong> syntactic restriction on the attributes <strong>in</strong> the <strong>select</strong> clause holds also for<br />

queries that would be semantically correct (i.e., for which there is only a<br />

s<strong>in</strong>gle value of the attribute for every group).<br />

Example: Fathers with their <strong>in</strong>come and with the average <strong>in</strong>come of their<br />

children.<br />

Incorrect:<br />

<strong>select</strong> fc.father, avg(c.<strong>in</strong>come), f.<strong>in</strong>come<br />

from person c jo<strong>in</strong> fatherChild fc on c.name=fc.child<br />

jo<strong>in</strong> person f on fc.father=f.name<br />

group by fc.father<br />

Correct:<br />

<strong>select</strong> fc.ather, avg(c.<strong>in</strong>come), f.<strong>in</strong>come<br />

from person c jo<strong>in</strong> fatherChild fc on c.name=fc.child<br />

jo<strong>in</strong> person f on fc.father=f.name<br />

group by fc.father, f.<strong>in</strong>come<br />

56

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

Saved successfully!

Ooh no, something went wrong!