使用select语句创建另一个表的重复行的表

时间:2014-05-15 16:12:35

标签: sql select teradata

我有一个表,其中一列包含不同的整数。
对于表中的每个整数,我想将其复制为数字位数 - 例如:

  

12345(5位数):
  1. 12345
  2. 12345
  3. 12345
  4. 12345
  5. 12345

我认为使用with recursion t (...) as ()来做这件事,但我没有管理,因为我真的不明白它是如何运作的,以及幕后发生的事情。
我不想使用insert,因为我希望它可以根据表格中的需要进行扩展和自动化。
任何想法和解释都会很棒。

3 个答案:

答案 0 :(得分:0)

最简单的方法是加入一个表格,其中包含从1到n的数字。

SELECT n, x
FROM yourtable
JOIN
 (
   SELECT day_of_calendar AS n 
   FROM sys_calendar.CALENDAR
   WHERE n BETWEEN 1 AND 12 -- maximum number of digits 
 ) AS dt
ON n <= CHAR_LENGTH(TRIM(ABS(x)))

在我的例子中,我滥用了TD的内置日历,但这不是一个好的选择,因为优化器不知道将返回多少行,并且由于计划必须是产品加入,它可能决定做一些愚蠢的事情。所以最好使用数字表...

答案 1 :(得分:0)

创建一个数字表,其中包含从1到表中数字所具有的最大位数的整数(我去了6):

create table numbers(num int)
insert numbers
select 1 union select 2 union select 3 union select 4 union select 5 union select 6

你已经有了你的桌子(但这里是我用来测试的):

create table your_table(num int)
insert your_table
select 12345 union select 678   

以下是获取结果的查询:

select ROW_NUMBER() over(partition by b.num order by b.num) row_num, b.num, LEN(cast(b.num as char)) num_digits
into #temp
from your_table b
cross join numbers n    

select t.num
from #temp t
where t.row_num <= t.num_digits

答案 2 :(得分:0)

我找到了一种很好的方法来执行此操作。这是:

with recursive t (num,num_as_char,char_n)
as 
(
    select   num
            ,cast (num as varchar (100)) as num_as_char
            ,substr (num_as_char,1,1)   

    from    numbers

    union all 

    select   num
            ,substr (t.num_as_char,2) as num_as_char2
            ,substr (num_as_char2,1,1)  

    from    t       

    where   char_length (num_as_char2) > 0
)

select  *
from    t
order by num,char_length (num_as_char) desc
相关问题