Link to home
Start Free TrialLog in
Avatar of TClevel
TClevelFlag for United States of America

asked on

T-SQL Union

how can I union a statment like this  to get a result like the bottom output

select a, b, c, count(*) As cars from table1
group by a
UNION
select a, b, c, Count(*) AS  houses from table2
group by a

I like the output to look something  like this

a          b            c       Cars    Houses
---       ----          ---     ------   ----------
john    Brown    car     2              2
Kim     Joins      car     3              3
ASKER CERTIFIED SOLUTION
Avatar of Rajkumar Gs
Rajkumar Gs
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Update UNION to UNION ALL. Otherwise data may not be correct.
select a, b, c, SUM(cars) AS cars, SUM(houses) AS houses
from
(
	select a, b, c, count(*) As cars, 0 as houses from table1
	group by a, b, c
	UNION ALL
	select a, b, c, 0 as cars, Count(*) AS  houses from table2
	group by a, b, c
) a
group by a, b, c

Open in new window


Raj
Avatar of TClevel

ASKER

Thank You
Welcome