我有这样的查询:
选择国家/地区,收入 来自mytable
结果是:
Usa, 1.000
Canada, 8.000
Japan, 2.000
我想添加百分比'重量',所以:
Usa, 1.000, 10%
Canada, 8.000, 80%
Japan, 1.000, 10%
在MySql中是否可以使用子查询?
由于
编辑:我很抱歉,百分比错了!现在我已经纠正了!答案 0 :(得分:1)
这个怎么样?
CREATE TABLE Table1
(`country` varchar(6), `revenue` decimal(4,3))
;
INSERT INTO Table1
(`country`, `revenue`)
VALUES
('Usa', 1.000),
('Canada', 8.000),
('Japan', 2.000)
;
select
t1.country, t1.revenue, concat(format(if(total.total = 0, 0, (t1.revenue / total.total * 100)), 2), ' %') as percent
from
Table1 t1
, (select sum(revenue) as total from Table1) total;
| COUNTRY | REVENUE | PERCENT |
|---------|---------|---------|
| Usa | 1 | 10.00 % |
| Canada | 8 | 80.00 % |
| Japan | 1 | 10.00 % |
答案 1 :(得分:1)
试试这个:
SELECT country, revenue
,CONCAT(FORMAT(IF(revenue =0,0,(revenue*100.0)/revenue_total_value),2),'%')
AS `percentage`
FROM (SELECT SUM(revenue) AS total_value FROM mytable)