简体   繁体   English

SQL 根据第一列的值对第二列进行排序

[英]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?这甚至可以在 SQL 查询中完成吗?

I think you want:你想要:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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