Skip to main content
Inspiring
March 16, 2009
Question

SQL Union

  • March 16, 2009
  • 2 replies
  • 795 views
I have a table by city, and population. I want to combine the populations of two cities into one. For example, the city of Ojai contains 10 people and the city of Santa Barbara contains 100 people. So for my output, I want to display the city as Santa Barbara and the population as 110

My query is something like this :

select sum(population), 'Santa Barbara' as city

from
(
select population from table where city='Ojai'
UNION
select populatoin from table where city='Santa Barbara'
)

It is giving me the population of the first record it finds, instead of both records.

Is using UNION not the right way to do it ?

I am going to try QofQ next.
    This topic has been closed for replies.

    2 replies

    Inspiring
    March 16, 2009
    > Yes, I get that now.

    Hmm... did you read the top section of the article? It describes two types of unions ..
    Inspiring
    March 16, 2009
    > Is using UNION not the right way to do it ?

    No. To understand why see:
    http://www.w3schools.com/sql/sql_union.asp
    trojnfnAuthor
    Inspiring
    March 16, 2009
    Yes, I get that now.

    I tried using QofQ and it gives me the same result, does not combine the two. What do I need to do to combine the population for both cities ?