如何計算SQL中的平均值?

[英]How to calculate average in SQL?


lets say I have the following table:

假設我有下表:

**FOOD**  | **AMOUNT**
  Bread   |   2
  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:

使用ANSI SQL(和SQL Server支持此語法),您可以執行以下操作:

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
('bread', 2)
,('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
bread           85          2            2.35
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
('bread', 2)
,('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

在這里你得到一個獲得PercentageOfTotal的方法,假設所有的總和不是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:

查詢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

Results:

結果:

|     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 |

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2017/12/19/b78f17f4a6883d2bcca6eb14c70c86ea.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com