Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Query to return count using group by?

Status
Not open for further replies.

rrchowdhary

Programmer
Aug 26, 2005
20
GB
I am having trouble getting the count of records from tableA

I need to find the LocationId whose count is < 5

here is the Sample Data

Code:
TableA
=======
LocationId
1
2
3


TableB
=======
LocationId	DocumentId

1		1000
1		1001
1		1002
1		1003
1		1004

2		1005
2		1006
2		1007
2		1008
2		1009
I need to get the LocationId whose count < 5 and, in this case i should get the LocationId 3 from Table A.

Thanks very much for any help.
 
Try this...

Code:
Select TableA.LocationId
From   TableA
       Left Join TableB 
         On TableA.LocationId = TableB.LocationId
Group By TableA.LocationId
Having Count(TableB.LocationId) < 5

If this works for you, and you would like me to explain it, just ask.

-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Yeah. I know. What's more interesting to me is.... do you understand it?



-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
This is what i have written initially and i am sure i understand your query

SELECT Locationid
FROM TableB
WHERE Locationid in
(
SELECT Locationid FROM TableA
)
GROUP BY Locationid
HAVING count(TableA.documentId) < 5

Thanks
 
Right. That query didn't work because there are NO records in TableB for LocationId = 3.

Another way you could have written this is...

Code:
SELECT Locationid
FROM   TableA
WHERE  Locationid Not In
(
    SELECT Locationid FROM TableB
    Group By LocationId
    Having Count(*) >= 5
)

This subquery method will be considerably slower than the Left Join method that I showed earlier. You may not notice a difference with small tables, but if your tables are large (or will become large) you will see the difference.



-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
you are right george, that's why i have used the query you have mentioned earlier, as i had to query the DB for nearly 500000 records..
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top