2012-02-15 16 views
0

我有這樣的一個表:MySQL的選擇查詢值

orderno  insurance 
ABC123  3.00 
ABC123  3.00 
ABC123  3.00 
DEF456  2.00 
DEF456  2.00 

我想要得到的平均保險值的總和爲每個唯一的順序。

例如(3.00+3.00+3.00)/3 + (2.00+2.00)/2

= 5 

我怎樣才能做到這一點使用MySQL查詢?

回答

2

試試這個:

SELECT SUM(avgIns) AS oAverage 
FROM 
    (SELECT OrderNo, AVG(Insurance) AS avgIns 
    FROM yourTableName 
    GROUP BY OrderNo) iTable 

UPDATE,如果你想限制你的小數位,使用FORMAT

(價值,decimalPlaces)

SELECT FORMAT(SUM(avgIns),2) AS oAverage   -- Returns two decimal places 
FROM 
    (SELECT OrderNo, AVG(Insurance) AS avgIns 
    FROM yourTableName 
    GROUP BY OrderNo) iTable 
+0

感謝您的理解,除了iTable之外,我應該怎麼做? – Chris 2012-02-15 02:13:44

+0

@chris'iTable'只是子查詢的名稱。 – 2012-02-15 02:15:49

+0

派生表和別名...明白了! – Chris 2012-02-15 02:15:53

0
select sum(value) from (
    select sum(insurance)/count(insurance) as value 
    from yourTableName 
    group by insurance 
) temp; 

實例運行在MySQL:

mysql> create table testTable (id int primary key auto_increment, orderno varchar(12), insurance decimal(6, 2)); 
Query OK, 0 rows affected (0.27 sec) 


mysql> insert into testTable (orderno, insurance) values ('ABC123', 3), ('ABC123', 3), ('ABC123', 3), ('DEF456', 2), ('DEF456', 2); 
Query OK, 5 rows affected (0.00 sec) Records: 5 Duplicates: 0 Warnings: 0 


mysql> select * from testTable; 
+----+---------+-----------+ 
| id | orderno | insurance | 
+----+---------+-----------+ 
| 1 | ABC123 |  3.00 | 
| 2 | ABC123 |  3.00 | 
| 3 | ABC123 |  3.00 | 
| 4 | DEF456 |  2.00 | 
| 5 | DEF456 |  2.00 | 
+----+---------+-----------+ 
5 rows in set (0.00 sec) 


mysql> select sum(value) from (  
select sum(insurance)/count(insurance) as value 
from testTable 
group by insurance) temp; 
+------------+ 
| sum(value) | 
+------------+ 
| 5.000000 | 
+------------+ 
1 row in set (0.02 sec) 
+0

這是行不通的。您無法按照使用聚合函數的同一列進行分組。 – Diego 2012-02-15 02:08:39

+0

是的,你可以......但我忘了給臨時表一個別名。 – jka6510 2012-02-15 02:15:47