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
 Transact-SQL (2000)
 Doing a count from a join which includes zeros

Author  Topic 

everbright
Starting Member

1 Post

Posted - 2007-04-20 : 00:58:25
Hi all,

I have 2 tables as follows:
Table A
id name department
1 Kev OSD
2 Roger LPD
3 Bim PWD
4 Conny PWD
5 Dan CPD

Table B
id table_a_id logindate
1 5 17/04/2007
2 1 16/04/2007
3 2 15/04/2007
4 2 16/04/2007

I want to form a query that retrives a count of unique user logins by departments, for a range of login dates.

So if I run the query for logins before 18/04/2007. I should get the following results

A.department Logins
OSD 1
LSD 1
PWD 0
CPD 1

Note that the count for LSD should be 1, although Kev logged in twice in the time period.

I tried some queries, but none was able to give me what I want. Most of these queries will drop the departments with no logins at all (i.e. no corresponding entries in table B).

Here's what I tried:

select A.department, count(distinct B.table_a_id) from A left outer join B on A.id=B.table_a_id where logindate < convert(datetime, '18/04/2007', 103) group by department

Anyone has done something similar and succeeded in getting the results?

Appreciate any help with this! Thanks!


khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-04-20 : 03:57:19
use LEFT JOIN

select A.department, Logins = isnull(B.id, 0)
from tablea A left join talbeb B
on A.id = B.id



KH

Go to Top of Page
   

- Advertisement -