如果选择sql的计数是> 0然后将结果与另一个sql的结果联合起来

时间:2016-02-01 10:11:28

标签: sql oracle

我有一个SQL如下:

SELECT
  ''                   AS "something1",
  'a pre defined text' AS "something2",
  ''                   AS "something3"
FROM dual

UNION ALL

SELECT
  rownum AS "something1",
  resultset.*
FROM (
       SELECT
         t1.abcd AS "something2",
         t2.xyz  AS "something3"
       FROM table_1 t1, table_2 t2
       WHERE t1.mnp = t2.mnp
       ORDER BY "something2"
     ) resultset;

此SQL生成如下结果:

something1      |      something2      |      something3
-------------------------------------------------------------
                 a pre defined text               
1                value of abcd from t1  value of xyz from t2
2                value of abcd from t1  value of xyz from t2

依旧......

结果中的第一行来自dual的第一行(第1行到第5行),其余的行来自UNION子句的第二行(第7行到第17行)。

现在挑战是如果从subsql(第7行到第17行)找到任何结果,则应该存在双(第1行到第5行)的结果。

例如,如果从subsql找到任何结果,那么最终输出将与上面相同,否则如下:

something1      |      something2      |      something3
-------------------------------------------------------------

有没有办法实现它?我尝试了一些方法,但没有成功。

2 个答案:

答案 0 :(得分:1)

您可以尝试在标准硬编码行上添加条件,只有在第二个选择返回任何行时才会显示,如下例所示:

select
  '' as 'something1',
  'a pre defined text' as 'something2',
  '' as 'something3'
from 
  dual
  where exists (select 1 from table_1 t1, table_2 t2 where t1.mnp = t2.mnp)
union all
select
  rownum as 'something1',
  resultset.*
from (
  select
    t1.abcd as 'something2',
    t2.xyz as 'something3'
  from 
    table_1 t1, table_2 t2
  where 
    t1.mnp = t2.mnp
  order by 
    'something2'
) resultset; 

答案 1 :(得分:0)

首先,请在发布之前修复代码中的所有明显问题:

  • 你在列别名周围使用单引号 - 这是非法的,并被SQL编译器拒绝
  • 不要在SQL语句中使用行号 - 它们使得复制和删除它变得不必要。运行声明
  • 考虑使用ANSI样式的JOIN而不是旧的Oracle语法

您的问题本身可以通过使用分析函数COUNT()来计算其something1为非NULL的行数来解决:

count(something1) over (partition by 1) as cnt

计算此计数后,您可以应用WHERE子句来过滤出cnt等于0的行。您的整体查询(稍微重写,带有示例数据):

 with table_1 as
 (select 'abcd from t1' as abcd,
         1 as mnp
    from dual),
table_2 as
 (select 'xyz from t2' as xyz,
         1 as mnp
    from dual),
resultset as
 (select t1.abcd as something2,
         t2.xyz  as something3
    from table_1 t1
    join table_2 t2
      on t1.mnp = t2.mnp
   order by something2),
resultset_plus_dummy as
 (select null as something1,
         'a pre defined text' as something2,
         '' as something3
    from dual
  union all
  select rownum as something1,
         resultset.*
    from resultset),
resultset_with_cnt as
 (select r.*,
         count(something1) over(partition by 1) as cnt
    from resultset_plus_dummy r)
select *
  from resultset_with_cnt
 where cnt > 0