具有空值时的SQL排序
我必须按数值升序排列sql结果。 我的代码是这样的:具有空值时的SQL排序,sql,decimal,numeric,Sql,Decimal,Numeric,我必须按数值升序排列sql结果。 我的代码是这样的: ORDER BY CAST(`baseData` AS DECIMAL(10,2)) {$dir} "; 它工作得很好,但有一个问题:它将所有空值放在底部,我认为它将它们视为“0”。 我需要在底部放置所有空值,如何修改它?试试这个SQL 对于MYSQL ORDER BY COALESCE(CAST(`baseData` AS DECIMAL(10,2)),0) 甲骨文 ORDER BY NVL(CAST(baseData AS DECIM
ORDER BY CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";
它工作得很好,但有一个问题:它将所有空值放在底部,我认为它将它们视为“0”。
我需要在底部放置所有空值,如何修改它?试试这个SQL
对于MYSQL
ORDER BY COALESCE(CAST(`baseData` AS DECIMAL(10,2)),0)
甲骨文
ORDER BY NVL(CAST(baseData AS DECIMAL(10,2)),0)
MySQL 5.5.30架构设置:
create table test(
t varchar(5)
);
insert into test
values('123'),('234'),('222'),(NULL);
select coalesce(cast(t as decimal(10,2)),0)
from test
order by coalesce(cast(t as decimal(10,2)),0);
| COALESCE(CAST(T AS DECIMAL(10,2)),0) |
----------------------------------------
| 0 |
| 123 |
| 222 |
| 234 |
查询1:
create table test(
t varchar(5)
);
insert into test
values('123'),('234'),('222'),(NULL);
select coalesce(cast(t as decimal(10,2)),0)
from test
order by coalesce(cast(t as decimal(10,2)),0);
| COALESCE(CAST(T AS DECIMAL(10,2)),0) |
----------------------------------------
| 0 |
| 123 |
| 222 |
| 234 |
:
create table test(
t varchar(5)
);
insert into test
values('123'),('234'),('222'),(NULL);
select coalesce(cast(t as decimal(10,2)),0)
from test
order by coalesce(cast(t as decimal(10,2)),0);
| COALESCE(CAST(T AS DECIMAL(10,2)),0) |
----------------------------------------
| 0 |
| 123 |
| 222 |
| 234 |
如果你想把所有的空都放在头上
ORDER BY CAST(`baseData` AS DECIMAL(10,2)) NULLS FIRST
如果要将所有空值都放在底部
ORDER BY CAST(`baseData` AS DECIMAL(10,2)) NULLS LAST
如果希望将空值视为0,请像Pheonix那样强制转换它们
ORDER BY Nvl(CAST(`baseData` AS DECIMAL(10,2)), 0) -- Oracle, MS SQL
ORDER BY IfNull(CAST(`baseData` AS DECIMAL(10,2)), 0) -- MySQL
如果希望空值是最后一个,但显示为0
select ...
Nvl(CAST(`baseData` AS DECIMAL(10,2)), 0) -- Oracle, MS SQL
...
order by CAST(`baseData` AS DECIMAL(10,2)) NULLS LAST
是的,它起作用了:
ORDER BY baseData = '', CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";
不,它会随机化结果(我使用的是MySql)更新后的答案在您的示例中没有order by子句。但是我应该把参数“asc”或“desc”放在哪里呢?最后一个空值之后或之前?按[Your Expression]排序ASC最后一个空值