Search code examples
sqlgroup-by

dbms sql query need to be correctly resolved


Retrieve the itemtype, category of item, and average price rounded to two decimal places of FMCG, Computer type items. The average price must be less than 2000.

ITEMCODE    ITEMTYPE    DESCR   PRICE   REORDERLEVEL    QTYONHAND   CATEGORY
I1001   FMCG    Britannia Marie Gold Cookies    20  100 1000    C
I1002   FMCG    Best Rice   120 100 1000    C
I1003   FMCG    Modern Bread    15  100 1000    C
I1004   Apparels    Lee T-Shirt 300 100 1000    B
I1005   Apparels    Levis T-Shirt   1700    100 1000    B
I1006   Apparels    Satyapaul Sari  7300    100 1000    A

is my query correct?

SELECT ItemType, Category, ROUND(AVG(Price),2) 
FROM Item 
WHERE (ItemType = 'FMCG') 
OR (ItemType = 'Computer') 
AND (Avg(Price) < 2000) 
GROUP BY ItemType;

Solution

  • Almost correct, you can't use aggregation functions in the WHERE clause, you should put them in a HAVING clause after the group by like this:

    SELECT ItemType, Category, ROUND(AVG(Price),2) 
    FROM Item 
    WHERE ItemType in('FMCG','Computer') 
    GROUP BY ItemType,Category;
    HAVING Avg(Price) < 2000
    

    I did a two adjustments to your query. First, when comparing the same column to more then 1 value, use IN instead of OR's.

    Secondly, I think the query should be grouped by category too, since its not always the same, but if you know that you shouldn't then delete it from the group by clause.