在同一查询中使用内部查询的结果

时间:2015-07-09 14:50:36

标签: sql

我试图在单独的计算中重用嵌套的选择查询别名PrevClose。但是我得到了无效的列名。这是否意味着无法重复使用结果,因为我需要对其进行一些计算,我必须再次重新运行内部查询两次?

 SELECT TOP 1000 [DateEntered]
      ,[Symbol]
      ,[Side]
      ,[Gross]
      ,[NET]
      ,[Shares]
      ,[Entry]
      ,[TimeIn]
      ,[Exit]
      ,[TimeOut]
      , B.Industry
      , (
        SELECT TOP 1 C.[Close] 
        FROM EndOfDay AS C 
        Where C.Symbol = A.Symbol 
            AND C.[Date] < A.DateEntered 
        ORDER BY C.[Date] DESC
      ) AS PrevClose
      , (A.[Entry] - PrevClose) AS Opg
  FROM [Analytics].[dbo].[TradeExec] AS A 
  Join finviz AS B ON A.Symbol = B.Ticker
  WHERE A.DateEntered < '2013-01-01'

2 个答案:

答案 0 :(得分:3)

要重用该值,请考虑将您的查询(减去带有计算的字段)并将其放在子查询中。然后,您可以使用外部查询中的子查询中的新列,并使用任意数量的计算。

SELECT *, (A.[Entry] - PrevClose) AS Opg
FROM (
    SELECT TOP 1000
    [DateEntered]
        ,[Symbol]
        ,[Side]
        ,[Gross]
        ,[NET]
        ,[Shares]
        ,[Entry]
        ,[TimeIn]
        ,[Exit]
        ,[TimeOut]
        , B.Industry
        , (
        SELECT TOP 1 C.[Close] 
        FROM EndOfDay AS C 
        Where C.Symbol = A.Symbol 
            AND C.[Date] = A.DateEntered 
        ORDER BY C.[Date] DESC
        ) AS PrevClose
    FROM [Analytics].[dbo].[TradeExec] AS A 
    Join finviz AS B ON A.Symbol = B.Ticker
    WHERE A.DateEntered < '2013-01-01'
) T

答案 1 :(得分:3)

使用outer apply

SELECT TOP 1000  . . .,
       prev.PrevClose,
       ( A.[Entry] - prev.PrevClose) AS Opg
  FROM [Analytics].[dbo].[TradeExec] A JOIN
       finviz B
       ON A.Symbol = B.Ticker OUTER APPLY
       (SELECT TOP 1 C.[Close] as PrevClose
        FROM EndOfDay C 
        WHERE C.Symbol = A.Symbol  AND C.[Date] = A.DateEntered 
        ORDER BY C.[Date] DESC
      ) prev
  WHERE A.DateEntered < '2013-01-01';

如果您愿意,这也可以让您从前一天获得多个列。