日期子集中的Min(),Max()

时间:2014-06-18 08:37:54

标签: oracle range max min

不确定标题是否合适,但这是我的问题: 我有下表:

create table OpenTrades(
AccountNumber   number,
SnapshotTime    date,
Ticket          number,
OpenTime        date,
TradeType       varchar2(4),
TradeSize       number,
TradeItem       char(6),
OpenPrice       number,
CurrentAsk      number,
CurrentBid      number,
TradeSL         number,
TradeTP         number,
TradeSwap       number,
TradeProfit     number  
);
alter table OpenTrades add constraint OpenTrades_PK Primary Key (AccountNumber, SnapshotTime, Ticket) using index tablespace MyNNIdx;

对于每个(SnapshotTime,帐户),我想选择min(OpenPrice),max(OpenPrice),使得相对于SnapshotTime,resultimg min和max仅相对于过去。 例如,对于任何可能的(账户,交易项目)对,我可能有10条记录,例如,Snapshottime = 10-jun和openprice在0.9和2.0之间,以及10条记录,其中SnapshotTime = 11-jun,openprice在1.0之间和2.1,以及10多条SnapshotTime = 12-jun和openprice在0.7和1.9之间的记录。 在这种情况下,所寻求的查询应返回如下内容:

AccountNumber  SnapshotTime  MyMin   MyMax
-------------  ------------  -----   -----
1234567        10-jun        0.9      2.0
1234567        11-jun        0.9      2.1
1234567        12-jun        0.7      2.1

我已经尝试过这个,但它只在同一个快照时间内返回min()和max():

select accountnumber, snapshottime, tradeitem, min(openprice), max(openprice) 
from opentrades 
group by accountnumber, snapshottime, tradeitem

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用min()max()的{​​{3}}以及窗口条款:

select distinct accountnumber, snapshottime, tradeitem,
  min(openprice) over (partition by accountnumber, tradeitem
    order by snapshottime, openprice
    rows between unbounded preceding and current row) as min_openprice,
  max(openprice) over (partition by accountnumber, tradeitem
    order by snapshottime, openprice desc
    rows between unbounded preceding and current row) as max_openprice
from opentrades
order by accountnumber, snapshottime, tradeitem;

ACCOUNTNUMBER SNAPSHOTTIME TRADEITEM MIN_OPENPRICE MAX_OPENPRICE
------------- ------------ --------- ------------- -------------
      1234567 10-JUN-14    X                    .9             2 
      1234567 11-JUN-14    X                    .9           2.1 
      1234567 12-JUN-14    X                    .7           2.1 

analytic versions

partition by根据accountnumber子句计算行子集中当前tradeitemrows between的值; order by表示它只会查看之前任何快照中的行,最高(min)或最高(max,因为desc)当计算每行的适当最小值/最大值时的当前快照。

计算每一行的分析结果。如果在没有distinct的情况下运行它,那么您会看到所有基本数据加上每个快照的相同最小值/最大值(SQL Fiddle)。由于您不希望任何不同的数据,您可以使用distinct来抑制重复,或者使用row_number()进行查询,然后将其过滤,等等。

答案 1 :(得分:0)

这能解决您的问题吗?

select ot1.accountnumber, ot1.snapshottime, ot1.tradeitem,
       min(ot2.openprice), max(ot2.openprice)
from opentrades ot1, opentrades ot2
where ot2.accountnumber = ot1.accountnumber
  and ot2.tradeitem = ot1.tradeitem
  and ot2.snapshottime <= ot1.snapshottime
group by ot1.accountnumber, ot1.snapshottime, ot1.tradeitem