获取最小,最大和当前价格

时间:2018-01-29 15:50:11

标签: sql oracle

我有一个包含以下数据的oracle数据库表。

Stock_name Current_Price Created_Date
---------- ------------- ------------
ABC        200        29-JAN-2018
ABC        195        28-JAN-2018
ABC        210        27-JAN-2018
ABC        175        26-JAN-2018
DEF        60         29-JAN-2018
DEF        10         28-JAN-2018
DEF        70         27-JAN-2018
DEF        80         26-JAN-2018

从这张表我想获取,股票名称,最低价格,最高价格和当前价格值,这里的当前价格是指表格中的最新价格。

这就是我试过的

 SELECT * FROM 
 (SELECT STOCK_NAME, MIN_PRICE, MAX_PRICE, (100 - ((MIN_PRICE/MAX_PRICE) *100)) AS PERCENTAGE_CHANGE FROM (SELECT STOCK_NAME, 
  MIN(CURRENT_PRICE) AS MIN_PRICE, MAX(CURRENT_PRICE) AS MAX_PRICE FROM 
  MKT_GOOD_STOCKS WHERE CREATED_DATE BETWEEN ADD_MONTHS(SYSDATE,-3) AND 
  SYSDATE GROUP BY STOCK_NAME ORDER BY STOCK_NAME)) ORDER BY 
  PERCENTAGE_CHANGE DESC;

2 个答案:

答案 0 :(得分:2)

这个怎么样:

select distinct Stock_name,
   min(Current_Price) over (partition by Stock_name),
   max(Current_Price) over (partition by Stock_name),
   LAST_VALUE(Current_Price) over (partition by Stock_name order by Created_Date)
from your_table;

另一种方法是:

select Stock_name.
   min(Current_Price),
   max(Current_Price),
   MAX(Current_Price) KEEP (DENSE_RANK LAST ORDER BY Created_Date)
from your_table
group by Stock_name;

答案 1 :(得分:1)

您希望每STOCK_NAME聚合值,因此您将按此列分组,并对其他值使用适当的聚合函数:

select
  stock_name,
  min(current_price) as min_price, 
  max(current_price) as max_price,
  max(current_price) keep (dense_rank last order by created_date) as last_price,
  100 - (min(current_price) / max(current_price) * 100) as percentage_change 
from mkt_good_stocks
group by stock_name
order by percentage_change desc;