【问题标题】:SQL - Ordering second column based on the first columnSQL - 根据第一列对第二列进行排序
【发布时间】:2020-12-23 18:43:41
【问题描述】:

我正在尝试从表中检索数据,但我需要以非常具体的方式对其进行排序,我不确定是否可以单独使用 Oracle SQL。

我需要做的是检索所有行,但是以第 3 列为空的方式对其进行排序(在下图中由空格表示),这些行首先排序。然后,第 3 列中所有不为空的行将显示在第 1 列中具有其列值的行之后。

我有什么:

+------+-------+------+
| Col1 | Col2  | Col3 |
+------+-------+------+
|    1 | text  |      |
|    2 | text  |    1 |
|    3 | text  |    1 |
|    8 | text  |   10 |
|    9 | text  |   10 |
|   10 | text  |      |
+------+-------+------+

我想要的结果:

+------+-------+------+
| Col1 | Col2  | Col3 |
+------+-------+------+
|    1 | text  |      |
|    2 | text  |    1 |
|    3 | text  |    1 |
|   10 | text  |      |
|    8 | text  |   10 |
|    9 | text  |   10 |
+------+-------+------+

我尝试过的:

我尝试的第一件事是使用:

ORDER BY coalesce(Col3, Col1)

它让我接近结果,但 Col1 值 10 需要在 Col3 值 10 之前显示。

+------+-------+------+
| Col1 | Col2  | Col3 |
+------+-------+------+
|    1 | text  |      |
|    2 | text  |    1 |
|    3 | text  |    1 |
|    8 | text  |   10 |
|    9 | text  |   10 |
|   10 | text  |      |
+------+-------+------+

我还尝试创建一个新列,如果 Col3 为空,则 Col4 为真,否则为假,但这与上面的合并基本相同。

我也尝试过只运行一些基本的订单,但没有成功。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    在 Oracle 中,您只需使用 nulls first:

    order by coalesce(col3, col1), col3 nulls first, col1
    

    【讨论】:

      【解决方案2】:

      您的表看起来很像分层数据,在某种意义上,col1 是唯一的行标识符,col3 指向行的父行。

      如果是这样,最好为此使用分层查询 (connect by)。排序是分层的,兄弟姐妹(来自同一父级的后代)根据order siblings by 子句进行排序。

      像这样:

      with
        sample_table(col1, col2, col3) as (
          select  1, 'text', null from dual union all     
          select  2, 'text',    1 from dual union all
          select  3, 'text',    1 from dual union all
          select  8, 'text',   10 from dual union all
          select  9, 'text',   10 from dual union all
          select 10, 'text', null from dual
        )
      select  *
      from    sample_table
      start   with col3 is null
      connect by col3 = prior col1
      order   siblings by col1
      ;
      
            COL1 COL2       COL3
      ---------- ---- ----------
               1 text           
               2 text          1
               3 text          1
              10 text           
               8 text         10
               9 text         10
      

      with 子句不是解决方案的一部分 - 我在那里添加了它,以便我可以测试查询。 (请记住这种“with 子句”创建用于测试的示例表的方式 - 您可以自己包含它们,而不是原始问题中的格式化表格,以便人们可以轻松地根据您的示例数据测试他们的答案。)

      【讨论】:

      • 有没有办法可以添加一个 where 子句“where Col1 = 10”来获取最后三行 (COL1 = {10, 8, 9})?通过在“开始于”中添加和 AND 解决了我自己的问题。谢谢!这实际上解决了我遇到的另一个问题。
      • @stackiee - 很可能,这应该放在start with 子句中,而不是where 子句中。试试start with col1 = 10 - 看看能不能回答你的问题。
      猜你喜欢
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      • 2014-12-02
      相关资源
      最近更新 更多