Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum values ​for each unique ID

I have a query that makes a set of relationships and gives me a number of rows that can be repeated for the same ID_PROD. The THEORETICAL_WEIGHT column will always be the same for a unique ID_PROD, and the REAL_WEIGHT column informs the actual weight that the product had when it was produced. This is my query:

    SELECT 
        A.ID_PROD,  A.REAL_WEIGHT, B.THEORETICAL_WEIGHT, 
        A.REAL_WEIGHT * B.THEORETICAL_WEIGHT AS Stock
    FROM 
        Table_A A,   
        Table_B B
    WHERE 
    B.ID_PROD = A.ID_PROD;

To find the weight we use, we need to multiply each product’s real weight value by the theoretical weight. My query above brings me values ​​like the ones below.

ID_PROD | REAL_WEIGHT | THEORETICAL_WEIGHT | Stock
 P01         1,5               3              4,5
 P01         0,3               3              0,9
 P01         5,1               3              15,3
 P02         2,1               2              4,2
 P02          3                2              6        
 P03          4                6              24

However, I want to improve this query, in a way that it only brings me a single row for each ID_PROD and in it, it already shows me the sum of the real weight of all the products of that ID_PROD, the theoretical weight value of that ID_PROD and the weight multiplication (real * theoretical weight). The expected result would be something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ID_PROD | REAL_WEIGHT | THEORETICAL_WEIGHT | Stock
   P01         6,9               3            20,7
   P02         2,1               2            10,2      
   P03          4                6            24

>Solution :

Aggregation, along with group by clause that contains columns that aren’t aggregated:

SELECT
    a.id_prod,
    SUM(a.real_weight) AS real_weight,
    b.theoretical_weight,
    SUM(a.real_weight * b.theoretical_weight) AS stock
FROM table_a a JOIN table_b b ON b.id_prod = a.id_prod
GROUP BY
    a.id_prod,
    b.theoretical_weight;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading