Sql Server - 使用计算字段连接子查询

时间:2011-05-20 01:06:05

标签: sql sql-server tsql

我正在尝试计算天数之间的价格变化百分比。由于日子不是连续性的,我在查询中构建了一个计算字段,告诉我它是相对的日子(第1天,第2天等)。为了将今天与昨天进行比较,我在子查询中将计算的日期数减去1。我想要做的是在计算的相对日加入内部和外部查询。我想出的代码是:

SELECT TOP 11 
       P.Date,
       (AVG(P.SettlementPri) - PriceY) / PriceY as PriceChange, 
       P.Symbol,
       (RANK() OVER (ORDER BY P.Date desc)) as dayrank_Today
FROM OTE P
  JOIN (SELECT TOP 11 
               C.Date, 
               AVG(SettlementPri) as PriceY, 
               (RANK() OVER (ORDER BY C.Date desc))+1 as dayrank_Yest
          FROM OTE C
         WHERE C.ComCode = 'C-' 
      GROUP BY c.Date) C ON dayrank_Today = C.dayrank_Yest
WHERE P.ComCode = 'C-' 
GROUP BY P.Symbol, P.Date 

如果我尝试执行查询,我会收到一条错误消息,指示dayrank_Today是一个无效列。我已经尝试过重命名它,对它进行鉴定,对它大喊大叫,然后我蹲下来。仍然是一个错误。

3 个答案:

答案 0 :(得分:3)

我遇到了同样的问题并找到了这个帖子并找到了解决方案,所以我想我会在这里发布。

不要使用列名作为 ON 的参数,而是复制首先为您提供colmun名称的语句:

取代:

ON dayrank_Today = C.dayrank_Yest

使用:

ON (RANK() OVER (ORDER BY Date desc)) = C.dayrank_Yest 

当然,你通过违反DRY来使编程之神不高兴,但是你可以务实并提及评论中的重复,这应该可以安抚他们的愤怒到轻微的抱怨。

答案 1 :(得分:2)

您无法选择计算列,然后在连接中使用它。您可以使用我不熟悉的CTE,或者您可以像这样选择表格选择:


SELECT 
     P.Date,       
     (AVG(AvgPrice) - C.PriceY) / C.PriceY as PriceChange, 
     P.Symbol,       
     P.dayrank_Today FROM
(SELECT TOP 11 
       ComCode,
       Date,
       AVG(SettlementPri) as AvgPrice,
       Symbol,
       (RANK() OVER (ORDER BY Date desc)) as dayrank_Today
FROM OTE WHERE ComCode = 'C-') P 
  JOIN (SELECT TOP 11 
               C.Date, 
               AVG(SettlementPri) as PriceY, 
               (RANK() OVER (ORDER BY C.Date desc))+1 as dayrank_Yest
          FROM OTE C
         WHERE C.ComCode = 'C-' 
      GROUP BY c.Date) C ON dayrank_Today = C.dayrank_Yest 
GROUP BY P.Symbol, P.Date 


答案 2 :(得分:1)

如果可能,请考虑使用CTE,因为它非常容易。像这样:

With Raw as
(
    SELECT TOP 11 C.Date,
    Avg(SettlementPri) As PriceY,
    Rank() OVER (ORDER BY C.Date desc) as dayrank
    FROM OTE C WHERE C.Comcode = 'C-'
    Group by C.Date
) 

select today.pricey as todayprice ,
yesterday.pricey as yesterdayprice,
(today.pricey - yesterday.pricey)/today.pricey * 100 as percentchange 
from Raw today
left outer join Raw yesterday on today.dayrank = yesterday.dayrank + 1

显然,这并不包含符号,但可以非常容易地包含该符号。 如果使用'With'语法不适合您也可以使用外部应用http://technet.microsoft.com/en-us/library/ms175156.aspx

计算字段

虽然CTE意味着你只需要编写一次更清洁的价格计算

干杯