简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM