[vox-tech] SQL help - unions

Henry House hajhouse at houseag.com
Tue Jul 20 17:03:40 PDT 2004


På tisdag, 20 juli 2004, skrev Peter Jay Salzman:
> Total newbie here.  I know less about SQL than I do about xkb.   ;-)
> 
> I have two tables, with the same structure.  Call them [Fall 2003] and
> [Spring 2004].  They each hold data about enrolled students.  One of the
> fields of these tables is SSN (social security number).
> 
> I can get an unduplicated headcount for the academic year with:
> 
>    SELECT SSN from [Fall 2003]
>    UNION
>    SELECT SSN from [Spring 2004];
> 
> There's also a field called "race".  If the race field is 0, the student
> is African American.
> 
> How would I modify the above SQL statement to list the unduplicated
> headcount of all African Americans?  I would like to do something like:
> 
>    SELECT SSN from [Fall 2003]
>    UNION
>    SELECT SSN from [Spring 2004]
>    and race == 1;
> 
> but of course that doesn't work.  :)

You need to use the WHERE operator to introduce a list filtering criteria.

A subquery is an easy and fairly intuitive way to do this.

	SELECT * from (
		SELECT SSN from [Fall 2003]
		UNION
		SELECT SSN from [Spring 2004]
	) WHERE race = 1;

The following should work too:

	(SELECT SSN from [Fall 2004] WHERE race = 1)
	UNION
	(SELECT SSN from [Spring 2004] WHERE race = 1);

The parentheses are optional, there to show you the precedence of the UNION
operator.

It would be helpful to know what RDBMS (PostgreSQL, MySQL, ...) you are
using since they vary greatly in their SQL syntax and feature support.

-- 
Henry House
Please don't send me HTML mail! My mail system will reject it.
The unintelligible text that may follow is a digital signature.
See <http://hajhouse.org/pgp> to find out how to use it.
My OpenPGP key: <http://hajhouse.org/hajhouse.asc>.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://ns1.livepenguin.com/pipermail/vox-tech/attachments/20040720/2b7f42e7/attachment.bin


More information about the vox-tech mailing list