【问题标题】:Select Case, when no data return选择Case,无数据返回时
【发布时间】:2015-04-17 19:33:52
【问题描述】:

当我需要验证选择查询的返回是否为空或有值时,是否可以执行 SELECT CASE、解码、nvl 或其他查询功能? 例如,我有这个:

Record |  type  | id_customer
-------+--------+-------------
1      |    T   | cus1
2      |    A   | cus2
3      |    T   | cus3
4      |        | cus4

如果我这样做:

select decode(type,'T','Main','A','Adicional','none') from table where record=1;

我得到主。

如果我这样做:

select decode(type,'T','Main','A','Adicional','none') from table where record=4;

我没有。

但如果我这样做:

select decode(type,'T','Main','A','Aditional','none') from table where record=5;

我什么也得不到,而且是合乎逻辑的。所以,我需要在行存在时获取解码值,如果行不存在,我需要获取文本。

所以,我尝试使用 SELECT CASE,但无法使用 COUNT 获取值。比如这样:

SELECT 
CASE 
WHEN count(1)>0 THEN decode(type,'T','Main','A','Aditional','none')
ELSE '-'
END
FROM TABLE WHERE record=5;

并得到一个'-',或者如果记录为2,则相同,得到'附加'

非常感谢。

【问题讨论】:

    标签: plsql oracle10g


    【解决方案1】:

    您可以使用聚合函数minmax 外部表达式:

    select max(decode(type,'T','Main','A','Aditional','none')) 
    from table
    where record=5;
    

    如果查询返回一行,您将获得该行的值。如果查询返回 0 行,您将得到 NULL
    然后你可以用nvl替换NULL

    select nvl(max(decode(type,'T','Main','A','Aditional','none')), ' - ')
    from table
    where record=5;
    

    编辑
    另外,如果您需要从多个字符串中选择一个:

    select decode(max(decode(type,'T', 2, 'A', 1, 0)), 0, 'none', 1, 'Additional', 2, 'Main', null, ' - ')
    from table
    where record=5;
    

    【讨论】:

    • 但是如果查询是:select nvl(max(decode(type,'T','Main','A','Additional','none')), ' - ' ) 来自 (1,2) 中记录的表; ??如果类型不是数字。
    • @h3g0r_ 在这种情况下,根据以下文档计算最小值和最大值:docs.oracle.com/cd/B28359_01/server.111/b28286/…。在多行的情况下你需要哪种行为?
    • 返回类型 T 或 P 而不是 A。
    • 获取 T 而不是 A 并且如果查询返回 0 行,则获取 ' - '。例如,如果查询是A,A,T,A查询必须返回T,只有当都是A时,返回必须A。类似的东西。非常感谢:)
    • @h3g0r_ 这个查询现在返回什么?我检查并得到'Main'(这意味着T,对吗?)。
    【解决方案2】:

    这是一个选项:

    select decode(type,'T','Main','A','Aditional','none') 
      from table 
     where record = 5
     union all
    select '-'
      from dual 
     where not exists (select 1 from table where record = 5);
    

    它选择record = 5 的记录并将它们与'-' 统一,如果没有记录退出record = 5。看看这个Fiddle

    【讨论】:

    • 在Oracle10g中,表总行数为'-'的那个结果,因为union all一个不存在的东西就是表的总和。但是如果我添加一个 rownum
    • 括号也能解决这个问题吗? (在这里:sqlfiddle.com/#!4/039d4/10)我只有一个 Oracle 11R2 XE ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多