DB2:如何显示一个范围内的所有日期

DB2: How do I display all dates in a range

我想使用 DB2(在 iSeries 上)查询扩展一个范围。例如,我在 table

中有以下值
2016-10-01 2016-10-03 600

我希望输出为

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

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


Table (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    

我收到错误 "Column list not valid for table"。

我也试过了

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  

这是抛出错误"Keyword not allowed in recursive common table expression TEMP1."

我做了一个测试 -- 这适用于 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

试试这个

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