0

我有这样的数据:

===================
id | name    | year
1  | Andy    | 1993
2  | Carroll | 1987
3  | Steve   | -973
4  | John    | null
===================

我如何将数据排序为:

===================
id | name    | year
3  | Steve   | -973
4  | John    | null
2  | Carroll | 1987
1  | Andy    | 1993
===================
4

3 回答 3

3

如果year不是整数类型,则应用castcoalesce

select *
from yourtable
order by cast(coalesce(year,0) as int)

如果它是一个整数,那么coalesce单独就足够了:

select *
from yourtable
order by coalesce(year,0)

这会将null年份列中的值视为0


为什么有区别?数字作为文本的排序方式与数字不同,在这里您要对数字进行排序。

于 2018-08-07T12:05:14.337 回答
1

你似乎想当它year是。如果是这样的逻辑:0NULL

order by coalesce(year, 0)
于 2018-08-07T12:04:19.340 回答
1

回应关于希望首先对有效年份进行排序的评论,您可以将查询更改为:

SELECT *
FROM Table1
ORDER BY (COALESCE(year,-1) >= 0) DESC, COALESCE(year,0)

输出:

id  name        year
2   Carroll     1987
1   Andy        1993
3   Steve       -973
4   John        (null)

COALESCE(year,-1) >= 0年份 >= 0 将返回 1,否则返回 0,因此“有效”年份(年份 >= 0)将在列表中排在第一位。

编辑

ORDER BY要在无效年份之前排序(空)年份,请将

ORDER BY (COALESCE(year,-1) >= 0) DESC, COALESCE(year,-2147483648)

这将确保(空)值低于任何年份值,因此将在它们之前排序。

输出:

id  name        year
2   Carroll     1987
1   Andy        1993
4   John        (null)
3   Steve       -973
于 2018-08-07T12:43:53.530 回答