开发者

sql order by multiple columns with nulls

开发者 https://www.devze.com 2023-03-05 04:34 出处:网络
I have a resultes set that looks like the following in a table var(sorry for the poor formatting): RootID | RootName | ChildId | ChildName

I have a resultes set that looks like the following in a table var(sorry for the poor formatting):

RootID | RootName | ChildId | ChildName

1      |  Bob     |  null   |   null   

1      |  null    |    4    |   Tim

1      |  null    |    6    |   Cindy

2      |  Alice   |  null   |   null

2      |  null    |  7      |   Joe 

2      |  null    |    9    |   Jack

3      |  Frank   |  null   |   null 

3      |  null   开发者_如何学C |   17    |   ken

What I would like to do is order them by RootName ASC then ChildName ASC to get them in alphabetical order. Any suggestions? Thanks in advance


If it works for your application, I'd rewrite the query to get rid of the nulls. I can't help but think that

RootID | RootName | ChildId | ChildName  
1      |  Bob     |    4    |   Tim  
1      |  Bob     |    6    |   Cindy  
2      |  Alice   |  null   |   Joe   
2      |  Alice   |    4    |   Jack  
3      |  Frank   |    7    |   ken

Would be easier to work with. (Uh, that NULL for Alice/Joe is a typo, right?)


Erm... What about this?

select * from yourtable order by RootName ASC, ChildName ASC

You can use NULLS LAST and NULLS FIRST (at least in Oracle) to control, where the nulls should be placed in the sorting.


select rec_id,gr_id from jegad order by 1 desc

select isnull(rec_id,'-'),isnull(gr_id,'-') from jegad order by 1 desc

ORDER BY CASE WHEN Col Is NULL Then 1 Else 0 End, Col

0

精彩评论

暂无评论...
验证码 换一张
取 消