我有两个股票交易相关的日内表:
示例(只是假的价格和数量):
交易表
char, char, integer, number, number
Ticker time, milliseconds price qty
MSFT 09:10:02 800 23.45 10
MSFT 09:10:02 900 23.45 5
MSFT 09:10:06 600 23.42 1
最佳出价询问表
char, char, integer, number, number, number, number
Ticker time milliseconds bid bid_qty ask ask_qty
MSFT 09:10:02 850 23.42 50 23.45 4
MSFT 09:10:02 930 23.44 50 23.45 1
MSFT 09:10:02 980 23.41 49 23.45 1
MSFT 09:10:06 600 23.42 45 23.43 2
MSFT 09:10:06 700 23.42 25 23.43 2
MSFT 09:10:06 710 23.41 20 23.43 2
问题:从交易时间戳开始,我希望在此交易完成后找到第一个随后的最佳出价最佳询价记录。换句话说:这笔交易导致下一个订单情况。
正确的SQL语句应该如何?
重要提示:
所以在我上面的例子中,我需要有以下连接的查询结果:
Ticker time milliseconds price qty ba_time ba_milliseconds bid bid_qty ask ask_qty
MSFT 09:10:02 800 23.45 10 09:10:02 850 23.42 50 23.45 4
MSFT 09:10:02 900 23.45 5 09:10:02 930 23.44 50 23.45 1
MSFT 09:10:06 600 23.42 1 09:10:06 600 23.42 45 23.43 2
谢谢!
答案 0 :(得分:0)
with trade as (
select
ticker,
format('%s.%s', "time", milliseconds)::time(3) as "time",
price,
qty
from trade
), bba as (
select
ticker,
format('%s.%s', "time", milliseconds)::time(3) as "time",
bid,
bid_qty,
ask,
ask_qty
from bba
)
select distinct on (rn)
t.ticker, t.time, t.price, t.qty,
b.time as ba_time, b.bid, b.bid_qty, b.ask, b.ask_qty
from
(
select *,
row_number() over(order by "time") as rn
from trade
) t
inner join
bba b on t.ticker = b.ticker and t."time" <= b."time"
order by rn, b.time
如果表格有一天以上,您将需要时间戳中的那一天。