Search code examples
sqlcountcoalesce

count coalesce to count from two columns


I have two columns

product    productactual

and the following data:

shoes        NULL
slippers     NULL
shoes        sandals
slippers     NULL
sandals      shoes

I have to count the Number of products I am using Count (coalesce(Productactual,product)) but its not working any changes in query or new idea to count products in two columns.


Solution

  • If you want to count entries per product, you need to use your COALESCE expression as a grouping item:

    SELECT
      COALESCE(productactual, product) AS product,
      COUNT(*) AS productcount
    FROM atable
    GROUP BY
      COALESCE(productactual, product)
    ;