您好,请您帮我解决一下这个问题
我有一张这样的表
From_date to_date price Product 13-Apr-2012 15-Apr-2012 15 hammer 1-may-2012 7-May-2012 15 Scredriver
从这个表中,我应该派生一个新的字段calc_date - 它应该包含from_date和to_date之间的日期,每一行都要复制价格和产品数据
结果集:
From_date to_date calc_date price Product
13-Apr-2012 15-Apr-2012 13-Apr-2012 15 hammer
13-Apr-2012 15-Apr-2012 14-Apr-2012 15 hammer
13-Apr-2012 15-Apr-2012 15-Apr-2012 15 hammer
1-may-2012 5-May-2012 1-may-2012 15 Scredriver
1-may-2012 5-May-2012 2-may-2012 15 Scredriver
1-may-2012 5-May-2012 3-may-2012 15 Scredriver
1-may-2012 5-May-2012 4-may-2012 15 Scredriver
1-may-2012 5-May-2012 5-may-2012 15 Scredriver
我尝试的Sql没有获取所需的数据(结果集)
SELECT from_date,
TO_DATE,
from_date + (LEVEL - 1) AS calc_date,
price,
product
FROM (SELECT from_date,
TO_DATE,
price,
product
FROM details)
CONNECT BY LEVEL <= TO_DATE - (from_date - 1)
你能帮我查询一下,它提供了上面提到的理想结果集
答案 0 :(得分:2)
我倾向于建立一个足够大的数字表,然后使用它:
with numbers as (
select level - 1 as n
from dual
connect by level <= 500
)
select from_date, to_date, from_date + n.n as calc_date, price, product
from details d join
numbers n
on n.n <= to_date - from_date;
您也可以为每条记录执行此操作。我发现这更容易理解。
如果您担心范围,可以这样做:
with numbers as (
select level - 1 as n
from dual
connect by level <= (select max(to_date - from_date) + 1 from details)
)
select from_date, to_date, from_date + n.n as calc_date, price, product
from details d join
numbers n
on n.n <= to_date - from_date;