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

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Other SQL Server Topics (2005)
 Count result showing as 1 instead of 0
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

ianwooly0
Starting Member

8 Posts

Posted - 01/19/2015 :  08:25:28  Show Profile  Reply with Quote
Hi,

I have a statement below which is returning some data from one table and then a count for corresponding rows in another table. I get 5 results as I expect, 3 of them have a significant number in the count column but the other 2 are returning 1 as the count. These should be 0! Query is below, any ideas? Thanks


Edited by - ianwooly0 on 01/20/2015 07:06:15

gbritton
Flowing Fount of Yak Knowledge

2780 Posts

Posted - 01/19/2015 :  08:59:06  Show Profile  Reply with Quote
post the data you're working with.
Go to Top of Page

Ifor
Aged Yak Warrior

700 Posts

Posted - 01/19/2015 :  09:16:37  Show Profile  Reply with Quote
Your data is useless as it does not show your problem and is not consumable. (ie CREATE TABLE .. INSERT.. etc)

You are counting all the result set, not just table b.
Your first query should probably be something like:

SELECT a.Id, a.Name, COUNT (b.School_Type_Id) AS Total
FROM School_Type a
	LEFT JOIN School_To_School_Type b
		ON a.Id = b.School_Type_Id
GROUP BY a.Id, a.Name;
Go to Top of Page

ianwooly0
Starting Member

8 Posts

Posted - 01/19/2015 :  09:27:44  Show Profile  Reply with Quote
Thank you Ifor that has worked. My data couldnt have been that bad if you supplied the correct answer. 10/10 for sql knowledge, 3/10 for people skills.
Go to Top of Page

gbritton
Flowing Fount of Yak Knowledge

2780 Posts

Posted - 01/19/2015 :  09:58:50  Show Profile  Reply with Quote
@ianwooly0 your sample data is not useful because if you run your query against your sample data the problem does not occur. Ifor simply meant (as did I) post sample data that demonstrates the problem. Sorry if I was not specific.

FWIW "consumable" means that you should post CREATE TABLE statements for each table and INSERT INTO statements to populate the tables with sample data that demonstrates the problem.
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000