SQL Server:选择最小值并返回该min的所有列信息,而不使用CTE

时间:2015-07-03 01:42:38

标签: sql sql-server group-by

我之前回答了一个问题,但是当答案被应用时,我的tempdb.mdf文件膨胀到500多个演出。我正在使用一个大型数据库但不是那么大(所有表的总数大约是800演出)。

为了减小尺寸,我将日期缩小到1个表(避免连接)。

以下是我的查询:

SELECT
       cast ([date_] as date) date_
      ,cast ([expDate] as date) expDate
      ,[strike]
      ,[putCall]
      ,[eqId]
      ,[ivMid] iv
      ,[delta]
      ,[close_],
      MIN(ivMid) OVER (Partition by eqid, date_, expDate) as MinIV
FROM 
    [CRC].[dbo].[***minsmall]
GROUP BY 
    date_, expDate, strike, putCall, eqid, ivMid, delta, close_

它几乎让我到达了我想去的地方,除了我没有得到min(iv)的特定单行,而是将min(iv)作为列添加到所有行。

这是一个小样本:

date_    expDate       strike  putCall  eqId  iv   delta    close_      MinIV
2008-01-02  2008-01-19  25.000   C    7   0.9853    0.9788  37.380005   0.3472
2008-01-02  2008-01-19  25.000   P    7   0.9319    -0.0171 37.380005   0.3472
2008-01-02  2008-01-19  30.000   C    7   0.5727    0.9697  37.380005   0.3472
2008-01-02  2008-01-19  30.000   P    7   0.6316    -0.0451 37.380005   0.3472
2008-01-02  2008-01-19  35.000   C    7   0.3854    0.8062  37.380005   0.3472
2008-01-02  2008-01-19  35.000   P    7   0.4022    -0.2087 37.380005   0.3472
2008-01-02  2008-01-19  40.000   C    7   0.3472    0.199   37.380005   0.3472
2008-01-02  2008-01-19  40.000   P    7   0.366    -0.7918  37.380005   0.3472
2008-01-02  2008-02-16  25.000   C    7   0.6306    0.9752  37.380005   0.37
2008-01-02  2008-02-16  25.000   P    7   0.6463    -0.0281 37.380005   0.37
2008-01-02  2008-02-16  30.000   C    7   0.5146    0.9097  37.380005   0.37
2008-01-02  2008-02-16  30.000   P    7   0.5083    -0.0897 37.380005   0.37
2008-01-02  2008-02-16  35.000   C    7   0.4065    0.7136  37.380005   0.37
2008-01-02  2008-02-16  35.000   P    7   0.4127    -0.2923 37.380005   0.37
2008-01-02  2008-02-16  40.000   C    7   0.3801    0.3401  37.380005   0.37
2008-01-02  2008-02-16  40.000   P    7    0.37    -0.6735  37.380005   0.37

我想要的是简单地提取这一行:

2008-01-02  2008-01-19  40.000   C    7   0.3472    0.199   37.380005   0.3472
每个给定的" eqid,date_,expDate"组

我试着添加这句话:

where ivMid = MinIV

在group by语句之上,但我收到了一条错误消息

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

使用子查询:

SELECT t.*
FROM (SELECT cast([date_] as date) as date_, cast ([expDate] as date) as expDate,
             [strike], [putCall], [eqId], [ivMid] as iv, [delta], [close_],
             MIN(ivMid) OVER (Partition by eqid, date_, expDate) as MinIV
      FROM [CRC].[dbo].[***minsmall]
      GROUP BY date_, expDate, strike, putCall, eqid, ivMid, delta, close_
     ) t
WHERE iv = minIV;

您无法使用SELECT子句中WHERE中为SELECT}定义的列别名。