我试图像这样在MySQL中转换为Decimal:
CAST((COUNT(*) * 1.5) AS DECIMAL(2))
我正在尝试将表中的行数(乘以1.5)转换为点后两位数的浮点数。
SQL代码:
SELECT CONCAT(Guardian.title, ' ',
Guardian.forename, ' ',
Guardian.surname) AS 'Guardian Name',
COUNT(*) AS 'Number of Activities',
(COUNT(*) * 1.5) AS 'Cost'
FROM Schedule
INNER JOIN Child ON Schedule.child_id = Child.id
INNER JOIN Guardian ON Child.guardian = Guardian.id
GROUP BY Guardian
ORDER BY Guardian.surname, Guardian.forename ASC
产生错误:
#1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'CAST((COUNT(*) * 1.5) AS DECIMAL(12,2))' at line 1.
另一个尝试,这个演员也不起作用:
SELECT CONCAT(Guardian.title, ' ',
Guardian.forename, ' ',
Guardian.surname) AS 'Guardian Name',
COUNT(*) AS 'Number of Activities',
CAST((COUNT(*) * 1.5) AS DECIMAL(8,2)) AS 'Cost'
FROM Schedule
INNER JOIN Child ON Schedule.child_id = Child.id
INNER JOIN Guardian ON Child.guardian = Guardian.id
GROUP BY Guardian
ORDER BY Guardian.surname, Guardian.forename ASC
如何使用mysql从整数转换为十进制?
答案 0 :(得分:22)
来自MySQL文档:Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:
在标准SQL中,语法
DECIMAL(M)
等同于DECIMAL(M,0)
因此,您将转换为包含2位整数和0位小数的数字。试试这个:
CAST((COUNT(*) * 1.5) AS DECIMAL(12,2))
答案 1 :(得分:19)
将裸整数转换为十进制:
select cast(9 as decimal(4,2)); //prints 9.00
将整数8/5转换为十进制:
select cast(8/5 as decimal(11,4)); //prints 1.6000
将字符串转换为十进制:
select cast(".885" as decimal(11,3)); //prints 0.885
将两个int变量转换为十进制
mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)
mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)
mysql> select @myvar1/@myvar2; //prints 0.6250
将十进制转换回字符串:
select cast(1.552 as char(10)); //shows "1.552"
答案 2 :(得分:4)
DECIMAL
包含两个部分:Precision
和Scale
。因此,您的部分查询将如下所示:
CAST((COUNT(*) * 1.5) AS DECIMAL(8,2))
Precision
表示为值存储的有效位数。
Scale
表示小数点后可存储的位数。
答案 3 :(得分:0)
答案 4 :(得分:-1)
如果您需要很多十进制数字,在本例17中,我与您共享MySql代码:
这是计算:
=(9/1147)* 100
SELECT TRUNCATE((((CAST(9 AS DECIMAL(30,20))/ 1147)* 100),17);