从满足条件A的组中选择行。如果不是,请给我一行满足条件B的行

问题描述 投票:2回答:1

我提出了一个有趣的问题,过去几天一直困扰着我。假设您有以下数据结构:

Col1 |  Col2    | Col3 | Col4
100  | "Val1"   | 0    | 100
100  | "Val2"   | 1    | null
100  | "Val 3"  | 0    | null
101  |  "Val4"  | 0    | null
101  |  "Val5"  | 1    | null
102  |  "Val6"  | 0    | null

我需要一排Col4!=null。如果所有行'Col4null然后返回我Col3=1行,但如果Col4都是nullCol3=0,那么返回我任意一行。

所以上面数据的结果集看起来像,

Col1  |  Col2    |  Col3  | Col4
100   |  "Val1"  |   0    |  100
101   |  "Val5"  |   1    | null
102   |  "Val6"  |   0    | null

我知道这可以使用分析函数完成,通过Col1Col4Col3对它们进行排序,并使用分析函数获取每个组中的第一行,但我们使用的是不支持分析函数的内部ORM。

如果可以使用简单的SQL(JOIN,Case等)完成此操作,请告诉我。


编辑:

每组只有一行,其中Col4具有非空值,每组有一行,其中col31。此外,该组中的单行可以满足Col4而不是nullCol3=1的条件。

sql oracle
1个回答
2
投票

这个怎么样?每个CONDx CTE解决了一个条件。

  • COND1返回COL4不为null的行
  • COND2返回在COL1结果集中不存在COND1的行,并且COL4具有NULL(在这种情况下,不同值的计数= 0)和COL3 = 1
  • COND3就是剩下的一切

最终结果是所有这些的结合。

SQL> with test (col1, col2, col3, col4) as
  2    (select 100, 'val1', 0, 100  from dual union all
  3     select 100, 'val2', 1, null from dual union all
  4     select 100, 'val3', 0, null from dual union all
  5     select 101, 'val4', 0, null from dual union all
  6     select 101, 'val5', 1, null from dual union all
  7     select 102, 'val6', 0, null from dual
  8    ),
  9  cond1 as
 10    (select col1, col2, col3, col4
 11     From test
 12     where col4 is not null
 13    ),
 14  cond2 as
 15    (select col1, col2, col3, col4
 16     from test t
 17     where t.col1 not in (select col1 from cond1)
 18       and col1 in (select col1
 19                    from test
 20                    group by col1
 21                    having count(distinct col4) = 0
 22                   )
 23       and col3 = 1
 24    ),
 25  cond3 as
 26    (select col1, col2, col3, col4
 27       from test t
 28       where t.col1 not in (select col1 from cond1
 29                            union all
 30                            select col1 from cond2
 31                           )
 32    )
 33  select col1, col2, col3, col4 from cond1
 34  union all
 35  select col1, col2, col3, col4 from cond2
 36  union all
 37  select col1, col2, col3, col4 from cond3
 38  order by col1;

      COL1 COL2       COL3       COL4
---------- ---- ---------- ----------
       100 val1          0        100
       101 val5          1
       102 val6          0

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.