all groups > sql server programming > november 2006 >
You're in the

sql server programming

group:

UNION Select Count(*) from 3 tables with where clause on each


UNION Select Count(*) from 3 tables with where clause on each hals_left
11/16/2006 10:13:40 PM
sql server programming:
Hi waht is the syntax for the above, this only return 1 row instead of
3. Thanks.
Each table has dteExported column. Thanks.

select count(*) from tblA WHERE DateDiff(d,dteExported,GetDate())>1)
UNION
select count(*) from tblB WHERE DateDiff(d,dteExported,GetDate())>1)
UNION
select count(*) from tblC WHERE DateDiff(d,dteExported,GetDate())>1)
Re: UNION Select Count(*) from 3 tables with where clause on each Adi
11/16/2006 10:25:29 PM
There is a good chance that all the queries in the union get the same
results. Since the default for union query is to return distinct rows
only, you are getting only 1 row. If you'll modify the query and
instead of union, you write union all, you'll get 3 rows.

Of course this brings up another question - Are you sure that this is
the result set that you want? If you'll just get 3 numbers then how
would you know which number belongs to which query? I would modify the
query and add a constant in each query in the union that will contain
the table's name so I'll know which row came from which query in the
union

Adi


[quoted text, click to view]
RE: UNION Select Count(*) from 3 tables with where clause on each Krishnakumar S
11/16/2006 10:32:01 PM
Hi
The UNION operator removes duplicates. So if the three SELECT statement
returns same COUNT you get only one row when using UNION.
Use UNION ALL to get all the three rows. More information is available in BOL.
--
Krishnakumar S


[quoted text, click to view]
Re: UNION Select Count(*) from 3 tables with where clause on each Chris O'C via SQLMonster.com
11/17/2006 12:00:00 AM
You need UNION ALL and you should identify which table each row is from.

select count(*) AS Num, "tblA" AS TableName from tblA WHERE DateDiff(d,
dteExported,GetDate())>1)
UNION ALL
select count(*) AS Num, "tblB" AS TableName from tblB WHERE DateDiff(d,
dteExported,GetDate())>1)
UNION ALL
select count(*) AS Num, "tblC" AS TableName from tblC WHERE DateDiff(d,
dteExported,GetDate())>1)

--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server-programming/200611/1
Re: UNION Select Count(*) from 3 tables with where clause on each hals_left
11/20/2006 12:44:55 PM
Thanks, that works great.

[quoted text, click to view]
Re: UNION Select Count(*) from 3 tables with where clause on each Chris O'C via SQLMonster.com
11/21/2006 5:35:38 PM
[quoted text, click to view]

Glad to hear it. You're very welcome and good luck with the rest of your
project.

--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server-programming/200611/1
AddThis Social Bookmark Button