Solved

Query Help: Count Subcategories in Category

Posted on 2011-03-06
2
401 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
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

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

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

Suggested Solutions

This article  is about submitting  form through  ColdFusion.Ajax.submitForm to the action page and send a response back in JSON format which later can be decoded using ColdFusion.JSON.decode. By this way you can avoid the usual page refresh for subm…
The technique is by far very Simple! How we can export the ColdFusion query results to DOC file?  Well before writing this I researched a lot in Internet but did not found a good Answer anyways!  So i thought now i should share my small snippet w…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

828 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