MySql如何在数字格式后排序结果?

Posted

技术标签:

【中文标题】MySql如何在数字格式后排序结果?【英文标题】:MySql how to order results after a number format? 【发布时间】:2018-04-23 14:13:35 【问题描述】:

我想返回按 tcv SUM 的结果降序排列的结果。如果我删除 FORMAT() 函数,这很好用,但是当我将 FORMAT() 函数添加到 SUM 时,它会按前几位的顺序返回结果,而不是查看整个数字。

所以它会在 7,456,234.00 之前返回 87,400.00,因为 8 在 7 之后,这显然不是预期的结果。

SELECT
x.user as user, u.name, 
FORMAT(SUM(IF(x.stage IN ('Closed Won') AND x.close_date BETWEEN '2018-04-01 00:00:00' AND '2018-04-30', x.amount_base, 0)), 2) as tcv, 
FORMAT(SUM(IF(x.stage IN ('Closed Won') AND x.close_date BETWEEN '2018-04-01 00:00:00' AND '2018-04-30', x.mrr_base, 0)), 2) as mrr,
FROM table AS x 
LEFT JOIN users u ON x.owner = u.name WHERE x.resign_new = 'New' AND x.owner IN ("Name 1", "Name 2", "Name 3")  
GROUP BY x.owner   
ORDER BY tcv DESC

我需要适当的格式,因为数字需要用逗号分隔符格式化以提高可读性。

我做错了什么让 mysql 错误地返回我 ORDER BY?

【问题讨论】:

【参考方案1】:

sum 函数根据您要聚合的列的数据类型返回小数或双精度。因此,要对其进行正确排序,您可以删除 order by 中的格式子句。见下文。

SELECT
x.user as user, u.name, 
FORMAT(SUM(IF(x.stage IN ('Closed Won') AND x.close_date BETWEEN '2018-04-01 00:00:00' AND '2018-04-30', x.amount_base, 0)), 2) as tcv, 
FORMAT(SUM(IF(x.stage IN ('Closed Won') AND x.close_date BETWEEN '2018-04-01 00:00:00' AND '2018-04-30', x.mrr_base, 0)), 2) as mrr,
FROM table AS x 
LEFT JOIN users u ON x.owner = u.name WHERE x.resign_new = 'New' AND x.owner IN ("Name 1", "Name 2", "Name 3")  
GROUP BY x.owner   
ORDER BY (SUM(IF(x.stage IN ('Closed Won') AND x.close_date BETWEEN '2018-04-01 00:00:00' AND '2018-04-30', x.amount_base, 0))) DESC

【讨论】:

以上是关于MySql如何在数字格式后排序结果?的主要内容,如果未能解决你的问题,请参考以下文章

MYSQL数据库字母数字混合字段排序问题

如何连接多个表并将结果排序为类似 json 的格式

Mysql之 order by 排序

关于时间格式的转换,MYSQL,PHP,10位数字表示时间

如何在mysql查询中获得排序结果?

SQL如何对分组后的结果进行排序并且取前几名