我正在开发一个网站,要求我显示用户输入每天平均数量的图表。我已经有一个SQL查询,它会将此信息返回给我:
SELECT sum(number)/count(number) as average, date FROM stats WHERE * GROUP BY date
这给了我正在寻找的结果,但结果以三位小数精度给出。我想围绕这个数字。当然,我可以在PHP或我的模板引擎中完成它,但我很好奇是否有办法在数据库中完成所有这些。
有没有办法将输出转换为整数(在MySQL中)?
答案 0 :(得分:34)
SELECT
CAST(sum(number)/count(number) as UNSIGNED) as average,
date
FROM stats
WHERE *
GROUP BY date
答案 1 :(得分:20)
MySQL中CAST
的有效类型如下
BINARY[(N)]
CHAR[(N)]
DATE
DATETIME
DECIMAL[(M[,D])]
SIGNED [INTEGER]
TIME
UNSIGNED [INTEGER]
所以你可以使用
SELECT CAST(sum(number)/count(number) AS UNSIGNED) as average...
或SIGNED
如果SUM
部分可以加起来为负数。
答案 2 :(得分:6)
如何使用MySQL FORMAT
函数?
mysql> SELECT FORMAT(12345.123456, 4);
+-------------------------+
| FORMAT(12345.123456, 4) |
+-------------------------+
| 12,345.1235 |
+-------------------------+
1 row in set (0.00 sec)
mysql> SELECT FORMAT(12345.123456, 0);
+-------------------------+
| FORMAT(12345.123456, 0) |
+-------------------------+
| 12,345 |
+-------------------------+
1 row in set (0.00 sec)
答案 3 :(得分:5)
使用DIV
operator。
mysql> SELECT 5 DIV 2;
-> 2
整数除法。与FLOOR()类似,但BIGINT值是安全的。对于超出BIGINT范围的非整数操作数,可能会出现不正确的结果。
答案 4 :(得分:1)
SELECT convert(int, sum(number)/count(number)) as average,
date
FROM stats
WHERE * GROUP BY date
或
SELECT
CAST(sum(number)/count(number) as INT) as average,
date
FROM stats
WHERE *
GROUP BY date
答案 5 :(得分:0)
您的示例查询将更新为
SELECT round(sum(number)/count(number)) as average, date FROM stats WHERE * GROUP BY date