SQL | How to sum in same table but referring to different cell values As an example, I've a table like this:  

CREATE TABLE Sample
    (`id` int, `productName` varchar(7), `description` varchar(55), `quantity`int(10))
;

INSERT INTO Sample
    (`id`, `productName`, `description`, `quantity`)
VALUES
    (1, 'Cheese', 'GT', 10),
    (1, 'Cheese', 'GE', 10),
    (1, 'Cheese', 'GE', 10),
    (2, 'Ham', 'VD', 10),
    (3, 'Wine', 'EX', 5)
;


and I'm trying to get a result so that the calculation is different if the description is of value GT and GE or VD. I tried with union all, but it does not seem to work:  

SELECT x.productName, SUM(x.quantity)
  FROM ( SELECT productName, SUM(quantity*10)
        FROM Sample
        WHERE description IN ('GT', 'GE')
        UNION ALL
        SELECT productName, SUM(quantity*20)
        FROM Sample
        WHERE description IN ('VD')
       ) AS x


Is this possible?
Don't forget GROUP BY clause when using aggregate functions.
Your inner SUMs aren't aliased, so x.quantity won't work.


Try this :

SELECT x.productName, SUM(x.quantity) as quantity
FROM 
(
    SELECT productName, SUM(quantity*10) as quantity
    FROM Sample
    WHERE description IN ('GT','GE')
    GROUP BY productName

    UNION ALL
    SELECT productName, SUM(quantity*20) as quantity
    FROM Sample
    WHERE description IN ('VD') 
    GROUP BY productName
) AS x
GROUP BY x.productName