以前行的SQL max

时间:2010-08-16 22:00:45

标签: sql sql-server tsql sql-server-2008-r2

我有Ticker,Dt,[Open],输入表的卷

Dt is yyyy-mm-dd

我想返回ticker ='IBM'的每一行,并返回Ticker,Dt,[Open],Volume字段,然后包含一个最大列,仅表示前几天的x。让我们说3天是为了不发布太多数据。

但是我不知道如何让时间框架正确,以便最多只包含这么多天。

在表格中:

Tck    Dt          [Open]      Volume   
IBM 2010-05-21  122.160000  6881000
IBM 2010-05-24  125.260000  6876000
IBM 2010-05-25  121.470000  9498800
IBM 2010-05-26  124.890000  9085900
IBM 2010-05-27  125.050000  7726500

我需要什么:

Tck    Dt          [Open]      Volume  Max
IBM 2010-05-21  122.160000  6881000 122.160000
IBM 2010-05-24  125.260000  6876000 125.260000
IBM 2010-05-25  121.470000  9498800 125.260000
IBM 2010-05-26  124.890000  9085900 125.260000
IBM 2010-05-27  125.050000  7726500 125.050000

这是我当前的SQL,但显然没有正确地对Max值进行分组。

Select Ticker, 
       Dt, 
       [Open], 
       Volume,
       (Select Max([Open]) from Daily_NYSE
            where Ticker = 'IBM'
            and Dt between DateAdd(Day,-3,'2010-05-27') and '2010-05-27') as 'Max'
from Daily_NYSE
where Ticker = 'IBM'
and Dt between DateAdd(Day,-6,'2010-05-27') and '2010-05-27' 

谢谢! 亚当

3 个答案:

答案 0 :(得分:2)

你的意思是这样吗?

编辑过去3个交易日工作

SELECT * INTO #stocks FROM 
(
SELECT 'IBM' AS Ticker, CAST('2010-05-21' AS DATE) AS dt, 122.160000 AS [OPEN] ,12639500 AS Volume UNION ALL
SELECT 'IBM' AS Ticker, CAST('2010-05-24' AS DATE), 125.260000 AS [OPEN] ,6876000 AS Volume UNION ALL
SELECT 'IBM' AS Ticker, CAST('2010-05-25' AS DATE), 121.470000 AS [OPEN] ,9498800 AS Volume UNION ALL
SELECT 'IBM' AS Ticker, CAST('2010-05-26' AS DATE), 124.890000 AS [OPEN] ,9085900 AS Volume UNION ALL
SELECT 'IBM' AS Ticker, CAST('2010-05-27' AS DATE), 125.050000 AS [OPEN] ,7726500 AS Volume 
) X

;WITH NumberedStocks AS
(
SELECT Ticker, dt, [Open], Volume, 
     ROW_NUMBER() OVER (PARTITION BY Ticker ORDER BY dt) AS rn
FROM #stocks
)
SELECT ns1.Ticker, ns1.dt, ns1.[Open], ns1.Volume, MAX(ns2.[Open]) AS MaxPrev3
FROM NumberedStocks ns1 LEFT JOIN NumberedStocks ns2
ON ns1.Ticker = ns2.Ticker AND ns2.rn 
   BETWEEN ns1.rn-3 AND ns1.rn-1 /*Or should this be ns1.rn-2 AND ns1.rn?*/
GROUP BY ns1.Ticker, ns1.dt, ns1.[Open], ns1.Volume

答案 1 :(得分:0)

我想我刚回答了自己的问题:

Select a.Ticker, 
       a.Dt, 
       a.[Open], 
       a.Volume,
       (Select Max([Open]) from Daily_NYSE b
            where Ticker = 'IBM'
            and b.Dt between DateAdd(Day,-2,a.Dt) and a.Dt) as 'Max'
from Daily_NYSE a
where Ticker = 'IBM'
and a.Dt between DateAdd(Day,-12,'2010-05-27') and '2010-05-27' 

答案 2 :(得分:0)

看起来您希望Max与给定日期前3天相对? 如果没有,请发表评论。

DECLARE @SomeDate smalldatetime    
SELECT @SomeDate = '2010-05-27'

SELECT Ticker, 
       Dt, 
       [Open], 
       Volume,
       (SELECT Max([Open]) 
            FROM Daily_NYSE AS D2
            WHERE D2.Ticker  = 'IBM'
            AND D2.Dt BETWEEN DateAdd(Day,-3,D1.Dt) AND D1.Dt
        ) AS 'Max'
FROM    Daily_NYSE AS D1
WHERE   Ticker = 'IBM'
AND     Dt BETWEEN DateAdd(Day,-6,@SomeDate) AND @SomeDate