查找数据的平均值到两个精度的小数位

时间:2018-10-18 14:51:14

标签: sql-server tsql sql-server-2008

我想将样本数据的平均值取到小数点后两位

DECLARE @TBL TABLE (Nos INT, Months VARCHAR(20), Duration INT)
INSERT INTO @TBL VALUES
(1,'Jan',33),(1,'Jan',107),(1,'Jan',36),(1,'Jan',139),(1,'Jan',140),(1,'Jan',5),(1,'Jan',130),
(1,'Jan',176),(1,'Jan',30),(2,'Feb',39),(2,'Feb',62),(2,'Feb',76),(2,'Feb',115),(2,'Feb',101),
(2,'Feb',12),(2,'Feb',139),(2,'Feb',174),(3,'Mar',5),(3,'Mar',59),(3,'Mar',72),(3,'Mar',100),(3,'Mar',153);

我的查询

SELECT
Nos,    
Months, 
AVG(Duration) AS [Average of Duration]
FROM @TBL
GROUP BY Nos,Months
ORDER BY Nos

当前输出

Nos Months  Average of Duration
1    Jan      88
2    Feb      89
3    Mar      77

预期产量

No  Month   Average of Duration
1    Jan      88.44
2    Feb      89.75
3    Mar      77.80

2 个答案:

答案 0 :(得分:3)

简单

DECLARE @TBL TABLE (Nos INT, Months VARCHAR(20), Duration INT)
INSERT INTO @TBL VALUES
(1,'Jan',33),(1,'Jan',107),(1,'Jan',36),(1,'Jan',139),(1,'Jan',140),(1,'Jan',5),(1,'Jan',130),
(1,'Jan',176),(1,'Jan',30),(2,'Feb',39),(2,'Feb',62),(2,'Feb',76),(2,'Feb',115),(2,'Feb',101),
(2,'Feb',12),(2,'Feb',139),(2,'Feb',174),(3,'Mar',5),(3,'Mar',59),(3,'Mar',72),(3,'Mar',100),(3,'Mar',153);

SELECT
Nos,    
Months, 
CAST(AVG(1.0 * Duration) AS DECIMAL(4, 2)) AS [Average of Duration]
FROM @TBL
GROUP BY Nos,Months
ORDER BY Nos;

结果:

+-----+--------+---------------------+
| Nos | Months | Average of Duration |
+-----+--------+---------------------+
|   1 | Jan    |               88.44 |
|   2 | Feb    |               89.75 |
|   3 | Mar    |               77.80 |
+-----+--------+---------------------+

答案 1 :(得分:2)

您可以使用avg添加显式算术:

SELECT Nos, Months, AVG(1.0 * Duration) AS [Average of Duration]
FROM @TBL
GROUP BY Nos, Months
ORDER BY Nos;