Search code examples
mysql

How to get SUM Quantity from mysql data with the same record


help me pliss I Have a table data in mysql like this:

mySQL table

my question; How to get SUM quantity from WIDTH column dan HEIGHT column base on same value (PHP / mySQL syntax)?

I want to get records (in bold ) like this;

10 = 26 (width = 26 + height = 0)

15 = 37 (width = 11 + height = 26)

20 = 36 (width = 16 + height = 20)

25 = 140 (width = 70 + height = 70)

Bad english, sorry....


Solution

  • First, group and sum by width, then group and sum by height, use left join to filter out unmatched height values, and sum the quantity of width and height.

    SELECT WIDTH, w.S + IFNULL(h.S, 0) AS QTY_SUM FROM
    (SELECT WIDTH, SUM(QTY) AS S FROM table_name GROUP BY WIDTH) w
    LEFT JOIN
    (SELECT HEIGHT, SUM(QTY) AS S FROM table_name GROUP BY HEIGHT) h
    ON w.WIDTH = h.HEIGHT
    ORDER BY w.WIDTH;