Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

union query 1

Status
Not open for further replies.

captlid

Technical User
Oct 27, 2004
82
US
is it possible to sum the results of a union all query?

example:

SELECT col1 FROM table WHERE col3 = 'value 1'
UNION ALL
SELECT col2 FROM table WHERE col4 = 'value 1'

can all the results from col1 and col2 be summed together?

thanks,
 
You could use a subquery (assuming MySQL 4.1):
[tt]
SELECT SUM(col1)
FROM
(
SELECT col1 FROM table WHERE col3 = 'value 1'
UNION ALL
SELECT col2 FROM table WHERE col4 = 'value 1'
)
u
[/tt]
or, a bit more exotic, and possibly slower, but works on earlier versions:
[tt]
SELECT SUM(col1*(col3='value 1')+col2*(col4='value 1'))
FROM table
[/tt]
 
Thank you so much :) especially for showing the query for versions before 4.1.

What does the asterik symbol denote?
 
Multiplication.

(col3='value 1') evaluates to either 1 or 0, true or false.
So, col1*(col3='value 1') evaluates either to the value of col1, or to zero.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top