DB2:如何显示范围中的所有日期

时间:2017-01-10 20:05:51

标签: db2 ibm-midrange db2-400

我想使用DB2(在iSeries上)查询扩展范围。例如,我在表中有以下值

2016-10-01 2016-10-03 600

我希望输出为

2016-10-01 200 
2016-10-02 200
2016-10-03 200

我试过,但我无法开发查询。它应该在下面类似的地方。

表(MYTABLE)有两列。下面是快照

START_DT    END_DT    
2016-01-01  2016-01-03

关于此查询

with temp1 as                                 
(                                             
  SELECT start_dt, end_dt, start_dt as dt     
  FROM mytable                                
    UNION                                     

  SELECT start_dt, end_dt, dt + 1 day as dt   
  FROM temp1                                  
  WHERE dt < end_dt                           
)                                             
SELECT dt                                     
FROM temp1    

我收到错误&#34;列列表对表格#34;无效。

我也试过这个

with temp1 (start_dt, end_dt, dt) as             
(                                                
  SELECT start_dt, end_dt, start_dt as dt        
  FROM mytable                                   
    UNION                                        

  SELECT start_dt, end_dt, dt + 1 day as dt      
  FROM temp1                                     
  WHERE dt < end_dt                              
)                                                
SELECT dt                                        
FROM temp1  

这是抛出错误&#34;递归公用表表达式TEMP1中不允许使用关键字。&#34;

2 个答案:

答案 0 :(得分:1)

我做了一个测试 - 这适用于9.7

with table1(start_dt,end_dt, amount) as
(
  values (timestamp('2017-01-01'), timestamp('2017-01-03'), 600)

), this_is_not_a_reserved_word (start_dt, end_dt, d, amount) as
(
  SELECT start_dt, end_dt, start_dt as d,
         amount/ (timestampdiff(16,end_dt-start_dt)+1) as amount
  FROM table1
--  WHERE tab_id_id = 518621     

    UNION ALL

  SELECT start_dt, end_dt, d + 1 day , amount
  FROM this_is_not_a_reserved_word
  WHERE d < end_dt
)
SELECT d, amount
FROM this_is_not_a_reserved_word

原始回答

你走了:

with this_is_not_a_reserved_word as
(
  SELECT start_dt, end_dt, start_dt as dt, amount/timestampdiff(16,start_dt-end_dt) as amount
  FROM table1
  WHERE tab_id_id = 518621     

    UNION 

  SELECT start_dt, end_dt, dt + 1 day as dt, amount
  FROM this_is_not_a_reserved_word
  WHERE dt < end_dt
)
SELECT dt, amount
FROM this_is_not_a_reserved_word

如果start_dt和end_dt是类型日期而不是时间戳使用:

amount/timestampdiff(16,timestamp(start_dt)-timestamp(end_dt)) as amount

答案 1 :(得分:0)

试试这个

with temp1  ( start_dt,   end_dt, DateCalc, num)  as                             
(                                             
  SELECT start_dt, end_dt, start_dt, 0  
  FROM  yourtable                                
  UNION  all                                   
  SELECT start_dt, end_dt,  DateCalc+ 1 day, num +1
  FROM temp1                                  
  WHERE DateCalc < end_dt                           
)                                             
SELECT DateCalc                                     
FROM temp1