0

甲骨文 11g

我想根据新成本的开始日期为每个成本设置结束日期

对于以下数据,请设置结束日期

输入:

Part number Site Cost           Start Date  End Date

000118-X    SR  8.926035461     10/1/2011   
000118-X    SR  10.7990022141   12/1/2011   
000118-X    SR  10.79900221     10/1/2012   
000118-X    SR  11.1574523796   12/1/2012   
000118-X    SR  11.15745238     10/1/2013   
000118-X    SR  14.054703823    12/1/2013   
000118-X    SR  16.4416037192   12/1/2014

期望的输出:结束日期是下一条记录的开始日期-1

Part number Site Cost           Start Date  End Date

000118-X    SR  8.926035461     10/1/2011   11/30/2011
000118-X    SR  10.7990022141   12/1/2011   09/30/2012
000118-X    SR  10.79900221     10/1/2012   11/31/2012
000118-X    SR  11.1574523796   12/1/2012   09/30/2013
000118-X    SR  11.15745238     10/1/2013   11/30/2013
000118-X    SR  14.054703823    12/1/2013   11/30/2014
000118-X    SR  16.4416037192   12/1/2014   
4

2 回答 2

2

您需要使用LEAD() 分析函数

有关架构设置,请参阅SQL Fiddle 演示

SQL> WITH cost AS
  2    (SELECT lead(start_date) OVER (ORDER BY start_date) rn,
  3      t.*
  4    FROM t
  5    )
  6  SELECT part_number ,
  7         site,
  8         cost,
  9         start_date,
 10         rn -1 end_date
 11  FROM cost;

PART_NUMBER SITE       COST START_DATE END_DATE
----------- ---- ---------- ---------- ----------
000118-X    SR        8.926 10/01/2011 11/30/2011
000118-X    SR         10.8 12/01/2011 09/30/2012
000118-X    SR         10.8 10/01/2012 11/30/2012
000118-X    SR        11.16 12/01/2012 09/30/2013
000118-X    SR        11.16 10/01/2013 11/30/2013
000118-X    SR        14.05 12/01/2013 11/30/2014
000118-X    SR        16.44 12/01/2014

7 rows selected.

SQL>
于 2015-09-01T05:31:06.540 回答
1

首先,您为每个元素分配一个行号

然后加入以将每一行与下一行匹配。
并减去一天的日期

SQL 小提琴演示

with cost as (
    SELECT         
        ROW_NUMBER() OVER (ORDER BY start_date) as R, t.*
    FROM testSQL t
)
SELECT 
    c1.part_number ,
    c1.site,
    c1.cost,  
    c1.start_date,
    c2.start_date - 1
FROM cost c1
left join cost c2 on c1.r = c2.r - 1
于 2015-09-01T04:14:20.530 回答