返回每个记录的4个略有不同的副本

时间:2016-09-20 15:18:37

标签: oracle concatenation repeat

我有一个庞大的,有点笨拙的Oracle查询,可以生成数千条记录。我现在必须添加一个新字段,为每条记录生成代码值。代码值的格式为:

<A|B><1|2><city>

此处,<city>是查询返回的字段。最终数据集需要每个记录有4个副本:例如,如果城市是波士顿,则代码值为:

A1Boston
A2Boston
B1Boston
B2Boston

这4条记录中的其他所有内容都必须相同,我必须为原始查询中的每条记录生成这4条记录。

除了(1)使用代码值组合生成临时表,然后加入它,或(2)选择变量并迭代它之外,是否有一种编程方式来执行此操作?我实际上必须为其他几个同样大的查询做同样的事情,所以我想做一些可重复的事情,如果可能的话。

谢谢!

3 个答案:

答案 0 :(得分:1)

假设代码值是静态的,也许这会让你知道如何做到这一点:

WITH sample_data AS (SELECT 1 ID, 'Boston' city FROM dual UNION ALL
                     SELECT 2 ID, 'New York' city FROM dual UNION ALL
                     SELECT 3 ID, 'Detroit' city FROM dual)
SELECT dummy1.col1||dummy2.col1||sd.city results
FROM   sample_data sd
       CROSS JOIN (SELECT 'A' col1 FROM dual UNION ALL
                   SELECT 'B' col1 FROM dual) dummy1
       CROSS JOIN (SELECT LEVEL col1
                   FROM   dual
                   CONNECT BY LEVEL <= 2) dummy2
ORDER BY sd.city, dummy1.col1, dummy2.col1;

RESULTS
-------------------------------------------------
A1Boston
A2Boston
B1Boston
B2Boston
A1Detroit
A2Detroit
B1Detroit
B2Detroit
A1New York
A2New York
B1New York
B2New York

通过使用两个交叉连接,如果代码值发生更改,则可以更轻松地修改查询,例如: &LT; A | B | C&GT;&LT; 1 | 2 | 3 | 4&GT;&LT;城市&GT; - 如果你硬编码要交叉连接的行(即'A1','A2','A3'等),你必须写出所有12种组合,而不是只使用代码中的7个指定值值。

答案 1 :(得分:0)

如果我了解您的需要,这可能是一种解决方法:

with test(something, city) as
(
    select 1, 'Boston' from dual union all
    select 1, 'Boston' from dual union all
    select 1, 'Boston' from dual union all
    select 1, 'Boston' from dual union all
    select 1, 'Boston' from dual union all
    select 6, 'N.Y.'   from dual union all
    select 6, 'N.Y.'   from dual union all
    select 6, 'N.Y.'   from dual union all
    select 7, 'L.A.'   from dual union all
    select 7, 'L.A.'   from dual
) 
select case when RN in (1, 2) then 'A' else 'B' end 
       ||
       case when RN in (1, 3) then '1' else '2' end,
       city,
       something
from (
        select city, something, row_number() over (partition by city order by null) as RN
        from test
     )
where RN <= 4         

答案 2 :(得分:0)

您可以使用子查询生成前缀值,然后将其与查询

连接
select 
  prefix || city, field1, field2 ...
from
  ( select city,  field1, field2 ... /* your query */ )
cross join
  ( select 'A1' as prefix from dual
    UNION ALL
     select 'A2' as prefix from dual
    UNION ALL
     select 'B1' as prefix from dual
    UNION ALL
     select 'B2' as prefix from dual
  )

选择