Connecting Tech Pros Worldwide Help | Site Map

Counting with an Inner Join.

Newbie
 
Join Date: Apr 2009
Posts: 9
#1: Oct 18 '09
I have two tables.

TBL_PRACTICE
Practice_ID (primary key)
Practice_Name
etc.

TBL_BRANCH
Branch_ID (primary key)
Branch_Name
Practice_ID
etc.

I need to create a view that has 2 fields. Practice Name, Number of Branches.

I have the following SQL, but this counts all the branches, not just the branches for this particular practice.

Expand|Select|Wrap|Line Numbers
  1. SELECT     TBL_PRACTICE.Practice_ID, TBL_PRACTICE.Practice_Name,
  2.     (SELECT count(TBL_BRANCH.Branch_ID) FROM TBL_BRANCH) AS Branches
  3. FROM TBL_PRACTICE INNER JOIN
  4.     TBL_BRANCH ON TBL_PRACTICE.Practice_ID = TBL_BRANCH.Practice_ID
If someone could let me know how I count only the branches for the corresponding Practice.

Thanks in advance, much appriciated.
mwasif's Avatar
Moderator
 
Join Date: Jul 2006
Location: Pakistan
Posts: 719
#2: Oct 18 '09

re: Counting with an Inner Join.


Use COUNT() and GROUP BY
Expand|Select|Wrap|Line Numbers
  1. SELECT TBL_PRACTICE.Practice_ID, TBL_PRACTICE.Practice_Name, COUNT(TBL_BRANCH.Branch_ID) AS Branches
  2. FROM TBL_PRACTICE INNER JOIN
  3. TBL_BRANCH ON TBL_PRACTICE.Practice_ID = TBL_BRANCH.Practice_ID
  4. GROUP BY Practice_Name
Reply