0

这是我的表的架构

CREATE TABLE [dbo].[HistoricalStockDetails]
(
    [CompanySymbol] [nvarchar](10) NOT NULL,
    [nDate] [datetime] NOT NULL,
    [Open] [money] NOT NULL,
    [High] [money] NOT NULL,
    [Low] [money] NOT NULL,
    [Close] [money] NOT NULL,
    [Volume] [bigint] NOT NULL,
    [sDate] [nvarchar](50) NOT NULL,
    [DMA200] [float] NULL,
    [DMA100] [float] NULL,
    [DMA20] [float] NULL,
    [DMA50] [float] NULL
) 

这是 30 行的样本数据。我想为每一行计算 20DMA 并更新它。

请建议我如何在 SQL Server 2008 R2 中执行此操作的简单方法。我尝试通过使用 CURSOR 来做到这一点,但由于大量数据,它非常耗时。我有 1800 只股票和所有的历史数据。现在我想计算 DMA 值并更新表。

提前致谢。

Symbol  nDate   Open    High    Low Close   Volume  sDate   DMA20  
A   11/18/99 12:00 AM   45.5    50  40  44  44739900    11/18/1999  NULL
A   11/19/99 12:00 AM   42.94   43  39.8    40.38   10897100    11/19/1999  NULL
A   11/22/99 12:00 AM   41.31   44  40.1    44  4705200 11/22/1999  NULL
A   11/23/99 12:00 AM   42.5    43.63   40  40  4274400 11/23/1999  NULL
A   11/24/99 12:00 AM   40.13   41.94   40  41.06   3464400 11/24/1999  NULL
A   11/26/99 12:00 AM   40.88   41.5    40.8    41.19   1237100 11/26/1999  NULL
A   11/29/99 12:00 AM   41  42.44   40.6    42.13   2914700 11/29/1999  NULL
A   11/30/99 12:00 AM   42  42.94   40.9    42.19   3083000 11/30/1999  NULL
A   12/1/99 12:00 AM    42.19   43.44   41.9    42.94   2115400 12/1/1999   NULL
A   12/2/99 12:00 AM    43.75   45  43.2    44.13   2195900 12/2/1999   NULL
A   12/3/99 12:00 AM    44.94   45.69   44.3    44.5    2175700 12/3/1999   NULL
A   12/6/99 12:00 AM    45.25   46.44   45.2    45.75   1610000 12/6/1999   NULL
A   12/7/99 12:00 AM    45.75   46  44.3    45.25   1585100 12/7/1999   NULL
A   12/8/99 12:00 AM    45.25   45.63   44.8    45.19   1350400 12/8/1999   NULL
A   12/9/99 12:00 AM    45.25   45.94   45.3    45.81   1451400 12/9/1999   NULL
A   12/10/99 12:00 AM   45.69   45.94   44.8    44.75   1190800 12/10/1999  NULL
A   12/13/99 12:00 AM   45.5    46.25   44.4    45.5    2875900 12/13/1999  NULL
A   12/14/99 12:00 AM   45.38   45.38   42.1    43  1665900 12/14/1999  NULL
A   12/15/99 12:00 AM   42  42.31   41  41.69   2087100 12/15/1999  NULL
A   12/16/99 12:00 AM   42  47.25   42  47.25   1848300 12/16/1999  NULL
4

1 回答 1

0

我不知道 DMA 是什么,但我认为你正在寻找这样的事情:

SELECT H1.nDate, AVG(H2.High) AS AverageHighLast20Rows

(SELECT nDate, RANK() OVER (ORDER BY nDate) AS Ranked FROM HistoricalStockDetails) H1
INNER JOIN
(SELECT nDate, High, RANK() OVER (ORDER BY nDate) AS Ranked FROM HistoricalStockDetails) H2
ON H2.Ranked BETWEEN H1.Ranked AND H1.Ranked - 20

GROUP BY H1.nDate
于 2013-10-04T06:51:56.233 回答