Oracle SQL占位符和生成文本

时间:2018-03-20 20:49:40

标签: sql oracle

请通过阅读我的场景和问题,帮助我更好地阐明这个问题。

我想知道以下情况是否可行:

我有一张这样的表:

ID # of APPLES
1  3
2 15
3 87
4 56 

还有另一张表:

ID Description
1 I have %d Apples
2 You have %d Apples

我想要的是从这两个表中获取数据,以便我的结果如下:

I have 3 Apples
I have 15 Apples
I have 87 Apples
I have 56 Apples
You have 3 Apples
You have 15 Apples
You have 87 Apples
You have 56 Apples

我的问题是,这可以在Oracle SQL中完成吗?

编辑:修改了结果的样子

3 个答案:

答案 0 :(得分:1)

如果您的结果有两行,那么您可以使用replace()join

select replace(t2.description, '%d', t1.num_apples)
from t1 join
     t2
     on t1.id = t2.id;

如果它有八行,您可以使用cross join

select replace(t2.description, '%d', t1.num_apples)
from t1 cross join
     t2
     on t1.id = t2.id;

要获得4行,我想你可以这样做:

select t.*
from (select replace(t2.description, '%d', t1.num_apples)
      from t1 cross join
           t2
           on t1.id = t2.id
      order by row_number() over (partition by t2.id order by t2.id)
     ) t
where rownum <= (select count(*) from t2);

这可以任意匹配值。我不清楚表中是否存在确定性逻辑。

答案 1 :(得分:0)

假设你的两个表是#temp3和#temp 4试试这个:

select replace(description, '%d', apples) from #temp3 a join #temp4 b on a.id=b.id

答案 2 :(得分:0)

您可以在 left的帮助下使用 right outer join &amp; ceil truncreplace &amp; lpad 函数和运算符:

select result from
 (
  select replace(l.Description,'%d',lpad(numApples,2,' ')) result, numApples
    from apples a left outer join lu_apples l on ( ceil(a.id/2) = l.id ) 
   union all
  select replace(l.Description,'%d',lpad(numApples,2,' ')) result, numApples
    from apples a right outer join lu_apples l on ( trunc(3-a.id/2) = l.id )  
 )  
order by result, numApples;

RESULT
---------------
I have 3 Apples
I have 15 Apples
I have 56 Apples
I have 87 Apples
You have 3 Apples
You have 15 Apples
You have 56 Apples
You have 87 Apples

Demo