偽の株式市場プログラムの買い手と売り手を照合するストアド プロシージャを作成しようとしています。最終的には、これを使用してトランザクション テーブルにデータを入力し、人々の注文を確定したいと考えています。これは、SQL Server エージェント ジョブにも含まれます。ここに私が持っているテーブルがあります:
Id UserId Type QtyRemaining Price CreatedOn
1 3 BUY 50 1.00 2012-09-09 05:25:48.4470000
2 6 BUY 50 1.00 2012-09-09 19:25:34.4300000
3 5 SELL 30 1.00 2012-09-09 19:22:59.5900000
4 3 SELL 50 0.90 2012-09-09 06:39:34.9100000
5 2 SELLALL 50 1.00 2012-09-09 04:10:01.8400000
これらの一致を行うには、いくつかの条件を満たす必要があります。
- 買い手は、「売り」注文の場合、買い手が希望する株式数以上の売り手を探す必要があります。「SELLALL」注文の場合、買い手が株式を購入するには数量が同じでなければなりません。例: 売り手は 50 株を売却する必要があり、買い手は同じ価格またはそれ以下の価格で 50 株を購入する必要があります。
- 買い手は、株式の最低価格を求めています。
- 上記の条件の売り手が複数いる場合、買い手は最低価格の後に最も古い売り株を最初に取得します。
したがって、トレーダーのペアは #1 と #4、#2 と #5 になります。したがって、#3 はまだ保留中です。
これは私が遊んでいたコードですが、最低価格と最も古いものを最初に適切に一致させることができません:
select o.*, oa.*, r.* from [Order] o
join OrderActivity oa on o.Id = oa.OrderId
join (
select o2.Id, o2.VideoId, o2.UserId, oa2.Price, oa2.QtyRemaining, o2.[Type] from [Order] o2
join OrderActivity oa2 on o2.Id = oa2.OrderId
where o2.Type = 'buy' and oa2.Status = 'open'
) as r on (o.VideoId = r.VideoId and oa.Price <= r.Price and r.QtyRemaining = oa.QtyRemaining and o.UserId != r.UserId)
where (o.Type = 'sell' or o.Type = 'sellall') and oa.Status = 'open'