Sunday, March 25, 2012

Count from multiple tables

I have 4 tables
One is a user table and the other three contain records for the users. They all have a USERNAME column
I would like to get a count of records for each table grouped by USERNAME

My output would be:
username,totalFrom1,totalFrom2,totalFrom3

Thanks For the help!Mybe something like:

select
username,
isnull(t1.ttlfrom1,0) ttlfrom1,
isnull(t2.ttlfrom2,0) ttlfrom2,
isnull(t3.ttlfrom3,0) ttlfrom3
from <users> u
left join
(
select username, count(username) ttlfrom1
from
<t1>
group by username
) t1 on t1.username = u.username
left join
(
select username, count(username) ttlfrom2
from
<t2>
group by username
) t2 on t2.username = u.username
left join
(
select username, count(username) ttlfrom3
from
<t3>
group by username
) t3 on t3.username = u.username
|||Thanks! I would never have figured that one out on my own, but I see how it works.
Thanks again
Greg

No comments:

Post a Comment