Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 2 tables, need a count on a column

Author  Topic 

sql777
Constraint Violating Yak Guru

314 Posts

Posted - 2005-11-24 : 17:50:06
My tables:

Table#1
userid

table#2

saleid userid cost


I want to do a select on table#1 and get the number of sales for the userid.

TIA

nr
SQLTeam MVY

12543 Posts

Posted - 2005-11-24 : 19:18:54
select userid, count(*)
from tbl2
group by userid

or if you want zeroes

select t.userid, sum(case when t2.userid is null then 0 else 1 end)
from tbl1 t
left join tbl2 t2
on t.userid = t2.userid
group by t.userid


==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

sql777
Constraint Violating Yak Guru

314 Posts

Posted - 2005-11-24 : 20:06:44
select userid, count(*)
from tbl2
group by userid

Are you missing a inner join??
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2005-11-24 : 22:18:42
quote:
Are you missing a inner join??

Not really. Depends on what you need.

If you only need to show userid with sales use the 1st query that nr suggested.

If you want to list all userid with number of sales including userid with 0 sales, use the 2nd query.

Hope that clear things up for u

-----------------
[KH]
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-11-25 : 00:02:54
If you use inner join then the userids that exist in table1 and not in table2 will be eliminated so you need to use Left join suggested by nr

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -