Oracle SQL返回最新和最近的最新价格和日期

时间:2017-04-13 13:16:27

标签: oracle greatest-n-per-group

我有ID列表,其中包含价格和日期(不同日期多次出现相同的零件号),并希望返回最近的价格日期和第二个最近的价格日期。我希望将价格和日期按列分开,这意味着我只需要出现一次ID。

例如(零件编号和价格是数字,PriceDate和价格结束日期是月,日,年格式的日期)

ID  Price PriceDate PriceEndDate
1   5.01  6/2/99    5/1/05
1   5.50  5/2/05    5/7/10
1   5.62  5/5/98    6/1/99
1   4.50  5/8/10    5/10/11
2   3.50  7/2/86    7/3/86
2   3.60  6/1/86    7/1/86
2   3.99  7/4/86    9/9/12
2   3.10  9/10/12   10/6/15
3   2.55  5/5/16    5/6/16
3   2.02  4/5/15    5/4/16
3   1.50  3/2/14    4/4/15

我需要返回的查询是

ID  Price PriceDate PriceEndDate SecondPrice SecPriceDate SecPriceEndDate
1   4.50  5/8/10    5/10/11      5.50        5/2/05       5/7/10
2   3.10  9/10/12   10/6/15      3.99        7/4/86       9/9/12
3   2.55  5/5/16    5/6/16       2.02        4/5/15       5/4/16

我见过SQL Server和MySQL的问题,但我目前正在使用Oracle SQL。谢谢!!

1 个答案:

答案 0 :(得分:2)

将数据作为行获取:

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY id ORDER BY priceEndDate DESC ) AS rn
  FROM   your_table t
)
WHERE  rn <= 2;

然后,PIVOT行到列可以执行:

SELECT id,
       "1_PRICE"          AS Price,
       "1_PRICESTARTDATE" AS PriceDate,
       "1_PRICEENDDATE"   AS PriceEndDate,
       "2_PRICE"          AS SecondPrice,
       "2_PRICESTARTDATE" AS SecPriceDate,
       "2_PRICEENDDATE"   AS SecPriceEndDate,
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY id ORDER BY priceEndDate DESC ) AS rn
  FROM   your_table t
)
PIVOT (
  MAX( price ) AS price,
  MAX( priceStartDate ) AS priceStartDate,
  MAX( priceEndDate ) AS priceEndDate
  FOR rn IN ( 1, 2 )
);