baris1892
baris1892

Reputation: 1051

Count frequency displaying also "0" values

I want to count and order the frequency of one main category (see SQLFiddle for table structures). But I want to display also "0" values, so if a categoryId isn't assigned by a product, this categoryId should have a frequency of "0".

My current SQL looks like this.

SELECT 
    category.categoryId,
    category.name,
    COUNT(*) AS frequency
FROM
    Categories category
        LEFT JOIN
    Product entry ON entry.categoryId = category.categoryId
WHERE
    category.parentId = 1
GROUP BY category.categoryId
ORDER BY COUNT(*) DESC

Result

| categoryId |             name | frequency |
|------------|------------------|-----------|
|          2 | Sub Category 1-2 |         3 |
|          4 | Sub Category 1-4 |         1 |
|          3 | Sub Category 1-3 |         1 |

If I make a RIGHT JOIN the category, which hasn't been assigned, will not be displayed at all (but I need it in the result).

The result I need should look like this:

| categoryId |             name | frequency |
|------------|------------------|-----------|
|          2 | Sub Category 1-2 |         3 |
|          4 | Sub Category 1-4 |         1 |
|          3 | Sub Category 1-3 |         0 |

Is there a way to display "0" frequency like in the result above?

SQLFiddle

Upvotes: 0

Views: 50

Answers (2)

Jens
Jens

Reputation: 69440

I think tis is the query you need:

SELECT 
    category.categoryId,
    category.name,
    COUNT(category.parentId) AS frequency
FROM
    Categories category
        LEFT JOIN
    Product entry ON entry.categoryId = category.categoryId
WHERE
    category.parentId = 1 or category.parentId is null
GROUP BY category.categoryId
ORDER BY COUNT(*) DESC

Upvotes: 1

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44844

You need to do count(entity.categoryId)

SELECT 
    c.categoryId,
    c.name,
    COUNT(e.categoryId) AS frequency
FROM
    Categories c
        LEFT JOIN
    Product e ON e.categoryId = c.categoryId
WHERE
    c.parentId = 1
GROUP BY c.categoryId
ORDER BY frequency DESC

Upvotes: 1

Related Questions