首页 > 解决方案 > MySQL - 如何比较从 CASE WHEN 返回的 varchar 小数?

问题描述

我有一个我希望首先排序的 sql country,然后每个country都有自己的排序规则。

这是我的sql:

select country, state, creditLimit, salesRepEmployeeNumber, customerNumber from customers
order by field(country, 'UK', 'france', 'USA') desc,
(
case when country = 'USA' then state
    when country = 'UK' then salesRepEmployeeNumber
    when country  = 'france' then creditLimit
    else customerNumber
end
);

问题是,creditLimit是类型decimal。但它看起来像case when转换decimalvarchar,并creditLimitvarchars 进行比较:

118200.00
123900.00
 21000.00
 53800.00
 61100.00
 65000.00
 68100.00
 77900.00
 81100.00
 82900.00
 84300.00
 95000.00

我考虑过将 varchars 转换回十进制,但是当它不是法国时,它们不应该作为小数进行比较。

如何解决这个问题?另外,我如何按降序对法国的 decimalLimit 进行排序?

标签: mysqlsql-order-bydecimalvarcharcase-when

解决方案


这里的问题是您尝试按单个CASE表达式排序,但有时您想使用文本列,有时您想使用小数列。你不能state十进制,但你可以做一个十进制文本。因此,这里的一种方法是将creditLimit小数列转换为文本,并用零填充它,以便它作为文本正确排序:

SELECT country, state, creditLimit, salesRepEmployeeNumber,
       customerNumber
FROM customers
ORDER BY
    FIELD(country, 'UK', 'france', 'USA') DESC,
    CASE country WHEN 'USA'    THEN state
                 WHEN 'UK'     THEN salesRepEmployeeNumber
                 WHEN 'france' THEN LPAD(creditLimit, 13, '0')
                 ELSE customerNumber END;

推荐阅读