### 如何計算SQL中的平均值？

#### [英]How to calculate average in SQL?

lets say I have the following table:

``````**FOOD**  | **AMOUNT**
Banana  |   5
Pizza   |   4
Apple   |   57
Mandarin|   9
Orange  |   8
``````

Final result:

``````  Bread  |  Percentage Of Total
Banana |  percentage of total
``````

etc etc

I tried it in every single way, but couldn't find a solution. I hope someone can help me.

## 6 个解决方案

### #1

2

Using ANSI SQL (and SQL Server supports this syntax), you can do:

``````select food, sum(amount),
sum(amount) / sum(sum(amount)) over () as proportion_of_total
from t
group by food;
``````

Note: Some databases do integer division, so you may need to convert to a floating point or fixed point type.

### #2

1

We can also try like below-

``````DECLARE @tbl AS TABLE
(
food VARCHAR(15)
,amount INT
)

INSERT INTO @tbl VALUES
,('banana', 5)
,('pizza', 4)
,('apple', 57)
,('mandarin', 9)
,('orange', 8)

SELECT
DISTINCT
food
,SUM(amount) OVER() TotalAmount
,SUM(amount) OVER (PARTITION BY food) PerFoodTotal
,CAST(SUM(amount) OVER (PARTITION BY food) * 100. / (SUM(amount) OVER()) AS DECIMAL(10,2)) [Percentage Of Total]
FROM @tbl
``````

OUTPUT

OUTPUT

``````food            TotalAmount PerFoodTotal Percentage Of Total
--------------- ----------- ------------ ---------------------------------------
apple           85          57           67.06
banana          85          5            5.88
mandarin        85          9            10.59
orange          85          8            9.41
pizza           85          4            4.71

(6 row(s) affected)
``````

### #3

0

You can try something like this:

``````declare @tbl as table (
food varchar(15)
,amount int
)

insert into @tbl values
,('banana', 5)
,('pizza', 4)
,('apple', 57)
,('mandarin', 9)
,('orange', 8)

select SUM(amount) from @tbl

select
food
,SUM(amount) as [food amount]
,(SUM(cast(amount as numeric(18,2))) / (select sum(cast(amount as numeric(18,2))) from @tbl)) * 100  as [Percentage Of Total]
,(select sum(amount) from @tbl) as total
from @tbl
group by food
``````

### #4

0

I think I need to be a little bit more specific.

Lets say I have two tables:

table1 and table2

table1和table2

``````**Table1**

'MusicGenres'
------------
Pop
Techno
Trance
trap
Hardcore
Electro

**Table2**

'SongID'       'MusicGenres'
----------------------------
1        |     Hardcore
2        |     Hardcore
3        |     Pop
4        |     Trap
5        |     Hardcore
6        |     Pop
7        |     Electro
8        |     Electro
9        |     Pop
10       |     Pop
11       |     Pop
``````

As a result I want something like this:

``````Pop     20% of total
Techno  0% of total
Trance  0% of total
trap    5% of total
Hardcore  40% of totl
Electro  55% of total
``````

### #5

0

Here you got a way fo getting the PercentageOfTotal, asuming that the sum of all will not be 0

``````DECLARE @total INT = (SELECT SUM(AMOUNT) FROM Table1)

SELECT FOOD, CAST((CAST((100 * AMOUNT) AS DECIMAL (18,2)) / @total  ) AS DECIMAL(18,2)) AS PercentageOfTotal from Table1
``````

### #6

0

SQL Fiddle

SQL小提琴

MS SQL Server 2014 Schema Setup:

MS SQL Server 2014架構設置：

``````CREATE TABLE MusicGenres (name varchar(10)) ;
INSERT INTO MusicGenres (name)
VALUES ('Pop'),('Techno'),('Trance'),('trap'),('Hardcore'),('Electro') ;

CREATE TABLE Table2 (SongID int, MusicGenres varchar(10)) ;
INSERT INTO Table2 (SongID, MusicGenres)
VALUES (1,'Hardcore')
,(2,'Hardcore')
,(3,'Pop')
,(4,'Trap')
,(5,'Hardcore')
,(6,'Pop')
,(7,'Electro')
,(8,'Electro')
,(9,'Pop')
,(10,'Pop')
,(11,'Pop')
;
``````

Query 1:

``````SELECT s1.name
, s1.recCount
, ( s1.recCount / CAST( ( SUM(recCount) OVER() ) AS decimal(5,2) ) )*100  AS pct
FROM (
SELECT m.name
, count(t.SongID) AS recCount
FROM MusicGenres m
LEFT OUTER JOIN Table2 t ON m.name = t.MusicGenres
GROUP BY m.name
) s1
``````

Could be shortened to

``````SELECT m.name
, count(t.SongID) AS recCount
, ( count(t.SongID) / CAST( ( SUM(count(t.SongID)) OVER() ) AS decimal(5,2) )
)*100  AS pct
FROM MusicGenres m
LEFT OUTER JOIN Table2 t ON m.name = t.MusicGenres
GROUP BY m.name
``````

``````|     name | recCount |     pct |
|----------|----------|---------|
|  Electro |        2 | 18.1818 |
| Hardcore |        3 | 27.2727 |
|      Pop |        5 | 45.4545 |
|   Techno |        0 |       0 |
|   Trance |        0 |       0 |
|     trap |        1 |  9.0909 |
``````