Search code examples
sqljoinsum

SQL: Trying to add up a total row which was calculated from 2 other columns


I'm attempting, and partly done, to find out how much stock is left in a business. I have a stock table and product price table that I'm pulling values from. The TOTAL column is quantityinstock * price which is what I need but I'd like to the get an overall total of the TOTAL.

How would I go about this? I've been searching for quite a while now to no avail!

I would like to, if possible get a TOTAL of TOTAL row adding up all of the TOTAL i.e. 3551.13 + 2941.91 + 2713.19 = VALUE.

SELECT
A.productID,
    quantityInStock,
    productPrice,
    quantityInStock * productPrice AS TOTAL
FROM gs_stock A
JOIN gs_productprice B ON A.productID = B.productID
WHERE endDate IS NULL
GROUP BY A.productID
ORDER BY TOTAL DESC

Sample Data:

+-----------+-----------------+--------------+---------+
| productID | quantityInStock | productPrice |  TOTAL  |
+-----------+-----------------+--------------+---------+
|        71 |             187 |        18.99 | 3551.13 |
|        73 |             109 |        26.99 | 2941.91 |
|        74 |             181 |        14.99 | 2713.19 |
+-----------+-----------------+--------------+---------+
SELECT
  A.productID,
  A.quantityInStock,
  B.productPrice,
  A.quantityInStock * B.productPrice AS TOTAL
FROM gs_stock A
JOIN gs_productprice B on A.productID = B.productID
WHERE endDate IS NULL
GROUP BY A.productID
ORDER BY TOTAL DESC

Solution

  • What I understood was that you need a total value of your stock that will be as follows:

    SELECT
      sum(TOTAL) as TOTAL_SUM
    FROM (
       SELECT
        A.productID,
        quantityInStock,
        productPrice,
        quantityInStock * productPrice AS TOTAL
       FROM gs_stock A
       JOIN gs_productprice B ON A.productID = B.productID
       WHERE endDate IS NULL
       GROUP BY A.productID
    ) TOTAL
    

    Added in TOTAL following the end bracket which then gave me the required calculation I was looking for!!! Cheers again, really appreciate your help!