Groups | Blog | Home
all groups > sql server programming > january 2007 >

sql server programming : Union Query Help!


Jami
1/21/2007 11:54:52 PM
Dear All!

i have following query

select count(distinct mid) from mytab
union
select count(distinct mid) from mytab_old
union
select count(distinct mid) from mytab_hist

this return me three out puts

100045
11245
334562


but i a single result sum of al these how will it b possible

regards,
Jami




ML
1/22/2007 12:23:01 AM
Try this:

select sum(derived.count_mid) as sum_count_mid
from (
select count(distinct mid) as count_mid from mytab
union
select count(distinct mid) from mytab_old
union
select count(distinct mid) from mytab_hist
) derived


ML

---
Alex Kuznetsov
1/22/2007 5:55:15 AM

[quoted text, click to view]

Hi Matija,

Just a minor correction: I think you should use UNION ALL instead of
UNION. Suppose there is exactly one row in each table - your original
query will return 1.

-----------------------
Alex Kuznetsov
http://sqlserver-tips.blogspot.com/
http://sqlserver-puzzles.blogspot.com/
Roy Harvey
1/22/2007 8:21:13 AM
Just for variety:

SELECT (select count(distinct mid) from mytab) +
(select count(distinct mid) from mytab_old) +
(select count(distinct mid) from mytab_hist)

Roy Harvey
Beacon Falls, CT

[quoted text, click to view]
AddThis Social Bookmark Button