簡體   English   中英

我們如何在 SQL 中將數字結果與字符串連接起來

[英]How we concatenate numeric result with a string in SQL

我想在 MySQL 接口中將 float 的結果與字符串對象連接起來,

我寫了這個查詢:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM