total rows

  • How to get total count of rows from 2 tables..in a single sql statement

  • Here's one way....

    select sum(c) as totalCount

    from  (

            select count(*) as c from table1

            union all 

            select count(*) as c from table2

          ) x

    /Kenneth

  • thks kenneth..could yu explain this a bit...is this a subquery? what is x at the end of query after )? Basically,i am just clueless..

    regards

    tal

  • How abt this....

    select (select count(*) from TableA )+(select count(*) from TableB ) as total

  • I'm sorry, it should have read like this to be (hopefully) a bit clearer..

    select sum(x.c) as totalCount

    from  (

            select count(*) as c from table1

            union all

            select count(*) as c from table2

          ) x

    The thing in between the parenthesises is a virtual table, and the 'x' is the name of the vitual table. You can view it like a 'temptable-on-the-fly' sort of.

    /Kenneth

  • thks kenneth..for clarification..thats great!!..i had no idea of virtual tables..any link on net where i can find more info?

    thks

  • They also go by the name 'derived tables'.

    You can find a good explanation here http://www.sqlservercentral.com/columnists/rmarda/derivedtablebasics_printversion.asp

    /Kenneth

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply