简体   繁体   中英

SQL Order Second Column Based on Value From First Column

I am trying to retrieve data from a table, but I need the resulting cursor to prioritize the ordering of the first row, then for each value in the first column I need it to check and add the rows from the second column based on that value.

From:

| Note | ID_1 | ID_2|
|------|------|-----|
| abc  |   1  | NULL|
| bcd  |   2  | NULL|
| ghu  |   3  | NULL|
| cde  |   4  |  2  |
| def  |   5  |  1  |

To:

| Note | ID_1 | ID_2|
|------|------|-----|
| abc  |   1  | NULL|
| def  |   5  |  1  |
| bcd  |   2  | NULL|
| cde  |   4  |  2  |
| ghu  |   3  | NULL|

I don't actually need it to reorder the table, I just need the cursor being returned to return the values in that order. I tried ordering it by the first column, then checking the second column, and a few other things, but I have not had any success.

SELECT * FROM TBL_X ORDER BY ID_1, ID_2

Is this even possible to do in a SQL Query?

I think you want:

select t.*
from t
order by coalesce(id_2, id_1), id_1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM