我们如何在SQL中将数字结果与字符串连接起来



我想将float的结果与MySQL中的字符串对象连接起来接口

我写了这个查询:

select name, concat(str(round(sum(amount_paid)/(select sum(amount_paid) from order_items)*100.0,2)) ,'%') as pct
from order_items
group by 1
order by 2 desc;

有人能给我一个可靠的查询吗,因为我好像遗漏了什么。

str()在MySQL中不是一个东西。concat()强制转换为字符串,因此您可以执行以下操作:

select name, 
concat(
round(
sum(amount_paid) / (select sum(amount_paid) from order_items) * 100,
2
), 
'%'
) as pct
from order_items
group by name
order by pct desc;

请注意,如果您运行的是MySQL 8.0,您可以使用窗口总和而不是子查询:

select name, 
concat(
round(
sum(amount_paid) / sum(sum(amount_paid)) over() * 100,
2
), 
'%'
) as pct
from order_items
group by name
order by pct desc;

最新更新