Sum of Two Union Queries

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Brent Wege

    #1

    Sum of Two Union Queries

    Hi I have the following union query that retrieves two counts. Can I
    sum them up within this query, like wrap this in a sum function
    somehow to get the total count? Or is there a better way to do this.
    Please help. Using SQL 2000.



    select count(user_id) from table1

    UNION

    select count(user_id) from table2
  • Steve Kass

    #2
    Re: Sum of Two Union Queries

    Brent,

    First, I'm guessing you don't really
    mean UNION here. If you did, you would
    get

    ----------
    40

    from your query if by chance each of table1
    and table2 contained 40 rows each with non-null
    user_id values.

    Because you mention UNION, I'm not sure whether
    you might want the total count of unique user_id
    values from the two tables, or just the sum of
    the counts.

    If you want the latter, just the sum of the counts,
    here is a possibility:

    select
    (select count(user_id) from table1)
    + (select count(user_id) from table2)
    as totalCount

    If you need to count user_id values only once when
    they appear in both table1 and table2, you can do this:

    select count(user_id)
    from (
    select user_id from table1
    union
    select user_id from table2
    ) T

    -- Steve Kass
    -- Drew University
    -- Ref: 68959432-090F-4058-8185-BE7DA62CBE6A



    Brent Wege wrote:[color=blue]
    > Hi I have the following union query that retrieves two counts. Can I
    > sum them up within this query, like wrap this in a sum function
    > somehow to get the total count? Or is there a better way to do this.
    > Please help. Using SQL 2000.
    >
    >
    >
    > select count(user_id) from table1
    >
    > UNION
    >
    > select count(user_id) from table2[/color]

    Comment

    • Brent Wege

      #3
      Re: Sum of Two Union Queries

      This helps a lot... thanks!

      Steve Kass <skass@drew.edu > wrote in message news:<eTtbb.530 93$NM1.7813@new sread2.news.atl .earthlink.net> ...[color=blue]
      > Brent,
      >
      > First, I'm guessing you don't really
      > mean UNION here. If you did, you would
      > get[/color]

      Comment

      Working...