【问题标题】:How to return a non null column from OracleDB如何从 OracleDB 返回非空列
【发布时间】:2015-03-17 17:01:27
【问题描述】:

我正在创建一个关于 Eclipse 的 birt 报告,我需要放置一个日期过滤器。 我在报告中有超过 1 个带日期的字段,其中一些为空。 问题是:如何使用正确的日期(非空)作为过滤器的参数?我正在尝试做这样的事情:

select
case 
when D___1 is null then
D___2
when D___2 is null then
D___3
when D___3 is null then
D___4
when D___4 is null then
D___5
end as data

然后这将返回一个有效日期,我将用作过滤器。但这似乎不起作用。有任何想法吗? 提前致谢。

【问题讨论】:

  • == 不是 SQL 中的运算符,检查 null 应该使用 IS NULL。
  • 感谢您的提醒。

标签: sql oracle birt


【解决方案1】:

您可以使用COALESCE 函数。它返回给定列表中的第一个“非空”值。

应该是这样的:

COALESCE(D___1, D___2, D___3, D___4, D___5) as DATA

【讨论】:

    【解决方案2】:

    您是否尝试显示 D1、D2、D3、D4、D5 中的第一个非空列?如果是这样,您最好使用COALESCE(D1, D2, D3, D4, D5)

    你的case语句不会像你期望的那样工作,因为

    a) "==" 在 Oracle 中不是有效的语法

    b) 比较 <something> = null(以及相应的 <something> != null)总是返回 null - 即。它既不是真的也不是假的。相反,您应该检查:<something> is null(反之:<something> is not null)。

    c) 您的逻辑不完整 - 您正在检查如果 D1 到 D5 为空该怎么办,而不是如果 D1(或 D2 或...)不为空会发生什么。

    假设您想要第一个非空值,这应该让您了解如何使用合并和案例逻辑来做到这一点:

    with sample_data as (select 1 col1, null col2, null col3 from dual union all
                         select null col1, 2 col2, null col3 from dual union all
                         select null col1, null col2, 3 col3 from dual union all
                         select null col1, 4 col2, 5 col3 from dual union all
                         select 6 col1, 7 col2, 8 col3 from dual union all
                         select 9 col1, null col2, 10 col3 from dual)
    select col1,
           col2,
           col3,
           coalesce(col1, col2, col3) first_non_null_coalesce,
           case when col1 is not null then col1
                when col2 is not null then col2
                when col3 is not null then col3
           end first_non_null_case_logic
    from   sample_data;
    
          COL1       COL2       COL3 FIRST_NON_NULL_COALESCE FIRST_NON_NULL_CASE_LOGIC
    ---------- ---------- ---------- ----------------------- -------------------------
             1                                             1                         1
                        2                                  2                         2
                                   3                       3                         3
                        4          5                       4                         4
             6          7          8                       6                         6
             9                    10                       9                         9
    

    【讨论】:

    • 非常感谢!我是软件领域的新手,你的例子对我帮助很大!我们需要更多这样的答案。
    猜你喜欢
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    相关资源
    最近更新 更多