为什么CROSS APPLY无法正常工作?

时间:2015-10-20 13:18:21

标签: sql sql-server

我创建了一个包含日期和资产价格的临时表。我想计算每日回报。当我使用LAG()时,它工作得很好,但是当我使用CROSS APPLY时,出现了问题。有人可以解释我的错误在哪里吗?

CREATE TABLE #returns (Data Date, s Float);

INSERT INTO #returns (Data, s) VALUES ('20120618', 142), ('20120619', 122), ('20120620', 145), ('20120621', 148), ('20120622', 111);

SELECT *
FROM #returns

SELECT Data, (s/LAG(s) OVER(ORDER BY Data) -1)
FROM #returns


SELECT tLater.Data, (tLater.s / tPrev2.s) - 1
FROM #returns as tLater
CROSS APPLY
   (
    SELECT TOP 1 tPrev.s
    FROM #returns as tPrev
    WHERE tPrev.Data < tlater.Data
    ORDER BY tPrev.Data
   ) as tPrev2

2 个答案:

答案 0 :(得分:3)

通常在<(或相关子查询)中使用CROSS APPLY时,您希望最大值而不是最小。我的猜测是你订购错了:

SELECT tLater.Data, (tLater.s / tPrev2.s) - 1
FROM #returns tLater CROSS APPLY
     (SELECT TOP 1 tPrev.s
      FROM #returns as tPrev
      WHERE tPrev.Data < tlater.Data
      ORDER BY tPrev.Data DESC
--------------------------^
     ) tPrev2;

答案 1 :(得分:3)

你在那里是alom,将cross apply更改为外部申请,而外部申请中的陈述应该是一个命令desc。

SELECT tLater.Data, (tLater.s / tPrev2.s) - 1
FROM #returns as tLater
OUTER APPLY
   (
    SELECT TOP 1 tPrev.s
    FROM #returns as tPrev
    WHERE tPrev.Data < tlater.Data
    ORDER BY tPrev.Data DESC
   ) as tPrev2