mysql - 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
转换decimal
为varchar
,并creditLimit
与varchar
s 进行比较:
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 进行排序?
解决方案
这里的问题是您尝试按单个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;
推荐阅读
- reactjs - 如何使用反应本机中的复选框检查 FlatList 中的单个项目?
- excel - Excel:以连续方式根据相邻单元格值自动编号单元格
- java - java / android:表格布局 - 特定列的可见性
- python - TensorFlow:从大文件中高效读取(和随机播放)样本
- arrays - NestJs 验证请求正文中的数组
- spring-boot - 如何在 Springfox 的 Swagger 2 中为字符串请求正文自定义模型?
- react-native - 在 React Native 中的 Android 上打开键盘时隐藏 ScrollView 下的组件?
- linux - 有没有办法在 linux 上使用命令行实用程序来获取 youtube 视频的前 5 条评论
- java - 接口数组
- sql - 多输出游标的 with 子句