简体   繁体   中英

how to add two columns of two different rows have one same field in MySQL?

I have a MySQL database: results:

ID           |    B_ID     |  SUM
------------ |-------------|---------
 1           |    400      |   10
 2           |    500      |   20
 3           |    500      |   30
 4           |    400      |   40

But i want this:

ID           |   B_ID      |  SUM
-------------|-------------|---------
 1           |    400      |   50
 2           |    500      |   50

Assuming that results is an actual table, you can query it as follows:

SELECT MIN(ID),
       B_ID,
       SUM(SUM)
FROM results
GROUP BY B_ID

If by "results" you mean that results is the output from another query, then, without knowing what your original table looks like, you could subquery as follows:

SELECT MIN(t.ID),
       t.B_ID,
       SUM(t.SUM)
FROM
(
    -- your original query goes here
) t
GROUP BY t.B_ID

SQL Fiddle

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