Search code examples
sqlgroup-bydb2ibm-cloudright-join

ERROR: SQL showing total quantity sold from product table and using RIGHT JOIN problem


Show total quantity sold from product table. Display product code, description, unit, quantity. Use RIGHT JOIN. Sort according to the most product sold.

this is my work. What is the problem of this

SELECT  sd.prodCode, SUM(sd.quantity) "total_quantity", p.prodCode, p.description, p.unit
FROM salesDetail sd
RIGHT JOIN product p 
ON p.prodCode = sd.prodCode
GROUP BY sd.prodCode
ORDER BY SUM(sd.quantity);

Error message An expression starting with "UNIT" specified in a SELECT clause, HAVING clause, or ORDER BY clause is not specified in the GROUP BY clause or it is in a SELECT clause, HAVING clause, or ORDER BY clause with a column function and no GROUP BY clause is specified..


Solution

  • As the error suggest:

    "UNIT" specified in a SELECT clause, HAVING clause, or ORDER BY clause is not specified in the GROUP BY clause

    You need to group the data by every field that you use on the SELECT statement that is not an aggregate function (like SUM(), AVG(), COUNT()).

    Like this:

    SELECT  sd.prodCode, p.prodCode, p.description, p.unit, SUM(sd.quantity) "total_quantity"
    FROM salesDetail sd
    RIGHT JOIN product p 
    ON p.prodCode = sd.prodCode
    GROUP BY sd.prodCode, p.prodCode, p.description, p.unit
    ORDER BY SUM(sd.quantity);