Solved

Query Help: Count Subcategories in Category

Posted on 2011-03-06
2
407 Views
Last Modified: 2012-06-21
I have a table that is setup with 3 columns

cat_id
cat_name
cat_parent_id

I want to just a list of the categories then show the count of subcats if they exist

So it may look like this

Category 1
Category 2(4)
Category 3(12)
Category 4(1)
Category 5
Category 6(3)
0
Comment
Question by:theideabulb
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 19

Expert Comment

by:Jones911
ID: 35048052
select count(cat_name) as catCount, catname
from tableName
group by cat_Name
0
 
LVL 52

Accepted Solution

by:
_agx_ earned 500 total points
ID: 35048281
If you want to include records with 0 subcategories, you'll need an OUTER JOIN.  

SELECT p.cat_name, COUNT(c.cat_id) AS SubCatCount
FROM   YourTable p 
            LEFT JOIN YourTable c ON p.cat_id = c.cat_parent_id
GROUP BY p.cat_name

Open in new window


To display top level categories only, add a filter. For example if top categories have a "cat_parent_id" of zero, then

SELECT p.cat_name, COUNT(c.cat_id) AS SubCatCount
FROM   YourTable p 
            LEFT JOIN YourTable c ON p.cat_id = c.cat_parent_id
WHERE p.cat_parent_id = 0 
GROUP BY p.cat_name

Open in new window

0

Featured Post

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Hi, I will be creating today a basic tutorial on how we can create a Mail Custom Function and use it where ever we want. The main advantage about creating a custom function is that we can accommodate a range of arguments to pass to the Function and …
Hi, Even though I have created this Tutorial on My personal Blog, Some people might not able to find my website, So here i am posting it again Today, from the topic it is very clear that i will be showing you here the very basic usage of how we …
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question