skip to Main Content

So I have this table:

table t1 i am querrying from

I am trying to produce a column that will look like this (containing the computed results)

table to be produced

I tried this query by it gives an error

SELECT Name, SUM(Amount) AS TAmnt, 
ProductPrice-SUM(Amount) AS OutB 
FROM t1
GROUP BY Name;

I tried this as well, but the results don’t seem to be what i want

SELECT Name,SUM(Amount) AS TAmnt, 
SUM(ProductPrice)-SUM(Amount) AS OutB 
FROM t1 
GROUP BY Name;

Any help to see what I am missing?

2

Answers


  1. You may try aggregating by name and product price:

    SELECT
        Name,
        SUM(Amount) AS TAmnt, 
        ProductPrice - SUM(Amount) AS OutB 
    FROM t1
    GROUP BY
        Name,
        ProductPrice;
    

    As mentioned by @Barmar, your current table is not normalized. Given that a product has only one price, you should create a separate prices table, and store this information there.

    Login or Signup to reply.
  2. Use ANY_VALUE() to prevent the error. It will select the ProductPrice value from any row in the group.

    SELECT Name, SUM(Amount) AS TAmnt, 
            ANY_VALUE(ProductPrice)-SUM(Amount) AS OutB 
    FROM t1
    GROUP BY Name;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search