简体   繁体   中英

SQL: Selecting sum of two columns across multiple rows

I have a table structure like this:

-------------------------------------
|  Country  |  Count 1  |  Count 2  |
-------------------------------------
|  USA      |  10       |  10       |
-------------------------------------
|  USA      |  10       |   10      |
-------------------------------------
|  France   |  200      |  200      |
-------------------------------------
|  USA      |  10       |  10       |
-------------------------------------
|  France   |  100      |  100      |
-------------------------------------

I would like to select the total of Count 1 and Count 2 for each country. So my output would be like

-------------------------
|  Country  |  Count    | 
-------------------------
|  USA      |    60     | 
-------------------------
|  France   |   600     |
-------------------------

Try using SUM()

SELECT Country,
 SUM(`Count 1` + `Count 2`) AS count
FROM table_name 
GROUP BY country

This is pretty straight-forward, you can use the aggregate function SUM() with a GROUP BY :

SELECT country, 
  sum(count1 + count2) as Total
FROM yourtable
GROUP BY country;

See Demo

Try this

SELECT Country, SUM(Count_1 + Count_2)
FROM Table 
GROUP BY Country

Try this.

UPDATE power 
  SET cnt = SUM(IFNULL(is_yellow, 0) + 
  IFNULL(is_green, 0) +  IFNULL(is_blue, 0));

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