简体   繁体   中英

How to sum up one of the column in MySQL table based on other columns

Below is the data that I have.

mysql> SELECT * FROM base
    -> ;
+----------+-----------+-------+------+
| ORD_DATE | PROD_CODE | WIDTH | QTY  |
+----------+-----------+-------+------+
| 20101001 | 0001      |    90 |    3 |
| 20101001 | 0001      |    90 |    3 |
| 20101001 | 0001      |   100 |    3 |
| 20101001 | 0001      |   100 |    3 |
| 20101001 | 0001      |   110 |   12 |
| 20101001 | 0001      |   120 |    3 |
| 20101001 | 0001      |   120 |    3 |
...
| 20101001 | 0002      |   955 |    5 |
| 20101001 | 0002      |   995 |    7 |
| 20101006 | 0001      |   385 |    6 |
| 20101006 | 0001      |   410 |    6 |
+----------+-----------+-------+------+

I would like to update above table by adding (QTY) of repeated rows that have same (ORD_DATE, PROD_CODE, WIDTH).

I would like to get the table data as below.

+----------+-----------+-------+------+
| ORD_DATE | PROD_CODE | WIDTH | QTY  |
+----------+-----------+-------+------+
| 20101001 | 0001      |    90 |    6 |
| 20101001 | 0001      |   100 |    6 |
| 20101001 | 0001      |   110 |   12 |
| 20101001 | 0001      |   120 |    6 |
...
| 20101001 | 0002      |   955 |    5 |
| 20101001 | 0002      |   995 |    7 |
| 20101006 | 0001      |   385 |    6 |
| 20101006 | 0001      |   410 |    6 |
+----------+-----------+-------+------+

Would you help please. Thanks.

If you want to keep the table as is, and want to only select the values as the second table, you could use the function SUM and the clause group by.

Ex.

SELECT ORD_DATE, PROD_CODE, WIDTH, SUM(QTY) FROM base
GROUP BY ORD_DATE, PROD_CODE, WIDTH;

But if you want to update the original table, you could use the above select, delete all the rows of the table, and reinsert using the information retrieved from the select.

select ORD_DATE, PROD_CODE, WIDTH, sum(QTY) from base group by ORD_DATE, PROD_CODE, WIDTH;

你可以参考演示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM