I have a table:
+------------+--------------+-------+------------+
| Name | Nation | Score | Game_date |
+------------+--------------+-------+------------+
| Ginobili | Argentina | 48 | 2005-01-21 |
| Irving | Australia | 44 | 2014-04-06 |
| Kirilenko | Soviet Union | 31 | 2006-11-11 |
| Kobe | USA | 81 | 2006-01-22 |
| LeBron | USA | 52 | 2014-12-06 |
| Mutombo | Congo | 39 | 1992-02-03 |
| Nowitzki | Germany | 48 | 2011-05-18 |
| PauGasol | Spain | 46 | 2015-01-11 |
| SteveNash | Canada | 42 | 2006-12-08 |
| TonyParker | France | 55 | 2008-11-06 |
| YaoMing | China | 41 | 2009-02-23 |
| YiJianlina | China | 31 | 2010-03-27 |
+------------+--------------+-------+------------+
I want to calculate the avg(score) of USA - avg(score) of China.
I have tried
select avg(score) from nba where nation = "USA" -
avg(score) from nba where nation = "China";
But it is wrong!
You can use AVG
and CASE WHEN
:
SELECT AVG(CASE WHEN nation = 'USA' THEN score END) -
AVG(CASE WHEN nation = 'China' THEN score END) AS result
FROM nba
WHERE nation IN ('USA', 'China');
Another option is to use UNION
:
SELECT SUM(sub.r) AS result
FROM ( SELECT avg(score) AS r
from nba
where nation = 'USA'
UNION ALL
SELECT -avg(score)
from nba
where nation = 'China') AS sub
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.