在SQL中选择/转换输出为整数

时间:2012-01-17 14:04:36

标签: mysql sql int

我正在开发一个网站,要求我显示用户输入每天平均数量的图表。我已经有一个SQL查询,它会将此信息返回给我:

SELECT sum(number)/count(number) as average, date FROM stats WHERE * GROUP BY date

这给了我正在寻找的结果,但结果以三位小数精度给出。我想围绕这个数字。当然,我可以在PHP或我的模板引擎中完成它,但我很好奇是否有办法在数据库中完成所有这些。

有没有办法将输出转换为整数(在MySQL中)?

6 个答案:

答案 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)

  1. 用户mysql函数round()
  2. 示例 round(23.33) 将在 msyql 中返回 23。

您的示例查询将更新为

SELECT round(sum(number)/count(number)) as average, date FROM stats WHERE * GROUP BY date