我有一张这样的表:
orderno insurance
ABC123 3.00
ABC123 3.00
ABC123 3.00
DEF456 2.00
DEF456 2.00
我想得到每个独特订单的平均保险价值总和。
e.g。 (3.00+3.00+3.00)/3 + (2.00+2.00)/2
= 5
如何使用MySQL查询实现此目的?
答案 0 :(得分:2)
试试这个:
SELECT SUM(avgIns) AS oAverage
FROM
(SELECT OrderNo, AVG(Insurance) AS avgIns
FROM yourTableName
GROUP BY OrderNo) iTable
<强>更新强>
如果您想限制小数位,请使用 FORMAT(value,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
答案 1 :(得分: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)