Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于从同一表返回另一行的SQL命令_Sql_Sql Server - Fatal编程技术网

用于从同一表返回另一行的SQL命令

用于从同一表返回另一行的SQL命令,sql,sql-server,Sql,Sql Server,我在SQL Server中有一个表,用于在同一个表中存储股票和衍生品 每个条目/行具有以下格式: ric、inst、price、ttime、strike和其他 ric是指不同的股票和衍生品的代码,即使它们指的是相同的股票 inst对于股票为0,对于看涨期权为1,对于看跌期权为2 strike是期权的执行价格,假设股票为0 价格是股票/期权的最后交易价格,ttime是交易时间 我想查询此结果: stockric | sttime | sprice | cric | cttime | cprice

我在SQL Server中有一个表,用于在同一个表中存储股票和衍生品

每个条目/行具有以下格式: ric、inst、price、ttime、strike和其他

ric是指不同的股票和衍生品的代码,即使它们指的是相同的股票

inst对于股票为0,对于看涨期权为1,对于看跌期权为2

strike是期权的执行价格,假设股票为0

价格是股票/期权的最后交易价格,ttime是交易时间

我想查询此结果:

stockric | sttime | sprice | cric | cttime | cprice
其中stockric=ric,sttime=ttime,sprice=inst=0的所有行的价格,即前3列为股票信息

对于每个股票信息,我想从同一个表中获得相应的信息ric、ttime、看涨期权的价格,我们称它们为cric、cttime、cprice

cric、cttime和cprice的条件为:

1.该行必须具有看涨期权的inst=1标识符,且cttime必须早于sttime

RIC代码必须符合特定标准

优先选择行权最接近股价的看涨期权,然后优先选择最近的交易

简言之,获取货币看涨期权的最后交易价格

根据Gordon Linoff先生的解决方案,我能够让代码正常工作

SELECT TOP (5) sp.ric as stockric, sp.ttime as sttime, sp.price as sprice, 
                sp2.ric as cric,sp2.strike as strikeverification, sp2.ttime as cttime, sp2.price as cprice
FROM [dbo].[swirepacific] sp CROSS APPLY
     (SELECT TOP (1) sp2.*
      FROM [dbo].[swirepacific] sp2
      WHERE sp2.inst = 1 and sp2.ttime <= sp.ttime and sp2.ric like substring(sp.ric,1,4) + '%'
      ORDER BY ABS(sp2.strike - sp.price), sp2.ttime desc
     ) sp2
WHERE sp.inst = 0
然而,令人担忧的是速度缓慢。在16c/96gb ram threadripper系统上运行约900000行x 8列表格需要16秒才能获得前5个结果。上述代码是否正确,性能是否有改进的余地


你的条件很难遵循。这还不清楚:

cric,cttime,cprice=ric,ttime,inst=1,STREAK=最接近sprice的行的价格,使用sprice下方的一个进行平局打破,cttime紧跟sttime之前

如果我将此理解为您想要最接近的执行价,那么一种方法是:


您的意思是要创建结果集,而不是表,对吗?表是否将新信息存储在数据库中的新表中?结果集是查询的结果。我还没有想到这个问题。我只需要在F/python中处理一次结果,然后就可以丢弃它。我想结果集更合适?为了清楚起见,我将编辑我的问题,谢谢您只能从嵌套查询标量子查询返回一个值。您必须为所需的每个值构造一个查询。因为我们没有任何测试数据或DDL可用于测试,也不知道结果应该是什么样子,所以我建议您可能只想将SELECT语句向下移动到交叉应用程序,看看这是否满足您的要求。这似乎就是你要问的。
SELECT sp.ric as stockric, sp.ttime as sttime, sp.price as sprice,
       sp2.*
FROM [dbo].[swirepacific] sp CROSS APPLY
     (SELECT TOP (1) sp2.*
      FROM [dbo].[swirepacific] sp
      WHERE sp2.stockric = sp.stockric AND
            sp2.inst = 1 
      ORDER BY ABS(sp2.strike - sp.price)
     ) sp2
WHERE inst = 0