SQL具有NULL值时的排序

时间:2013-06-02 11:41:49

标签: sql decimal numeric

我要通过升序数值来订购sql结果。 我的代码是这样的:

ORDER BY CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";

它工作得很好,但是有一个问题:它将所有NULL值放在底部,我认为它们认为它们像“0”。 我需要在底部放置所有NULL值,我该如何修改它?

3 个答案:

答案 0 :(得分:1)

试试这个SQL

对于MYSQL

ORDER BY COALESCE(CAST(`baseData` AS DECIMAL(10,2)),0)

对于Oracle

ORDER BY NVL(CAST(baseData AS DECIMAL(10,2)),0)

SQL Fiddle

MySQL 5.5.30架构设置

create table test(
t varchar(5)
);


insert into  test
values('123'),('234'),('222'),(NULL);

查询1

select coalesce(cast(t as decimal(10,2)),0)
from test
order by coalesce(cast(t as decimal(10,2)),0);

<强> Results

| COALESCE(CAST(T AS DECIMAL(10,2)),0) |
----------------------------------------
|                                    0 |
|                                  123 |
|                                  222 |
|                                  234 |

答案 1 :(得分:0)

如果你想把所有Null放在头上

  ORDER BY CAST(`baseData` AS DECIMAL(10,2)) NULLS FIRST 

如果你想把所有Null放在底部

  ORDER BY CAST(`baseData` AS DECIMAL(10,2)) NULLS LAST

如果您希望将Null视为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

如果你想让Null成为最后一个,但显示为0

  select ...
         Nvl(CAST(`baseData` AS DECIMAL(10,2)), 0) -- Oracle, MS SQL
         ...
   order by CAST(`baseData` AS DECIMAL(10,2)) NULLS LAST

答案 2 :(得分:0)

是的,它有效:

ORDER BY baseData = '', CAST(`baseData` AS DECIMAL(10,2)) {$dir} ";