如何在SQL Server中提取当前和过去一个月的数据

时间:2015-11-15 23:58:17

标签: sql sql-server sql-server-2014

我需要列出一年中每个月的交易日期和股票收盘价(我将称之为当前'月)和前一个月的股票收盘价。 '电流'月。

我正在使用的StockData表包含每个交易日期和股票代码的日期,股票高,低,开仓,收盘和交易量的列。

最初,我使用AVG

SELECT 
    YEAR(TradeDate) AS Year, 
    MONTH(TradeDate) AS Month, 
    TickerSymbol, 
    AVG(ST_Close) AS CurrentClose,
    LAG (AVG(ST_Close), 1, 0) OVER (ORDER BY TickerSymbol, YEAR(TradeDate), MONTH(TradeDate), TickerSymbol) AS PreviousMonthClose,
FROM 
    StockData
WHERE
    TradeDate >= '2000-01-01' AND ST_Close IS NOT NULL
GROUP BY 
    YEAR(TradeDate), MONTH(TradeDate), TickerSymbol
ORDER BY 
    YEAR(TradeDate), MONTH(TradeDate), TickerSymbol;

但是,不是使用平均值,而是希望从每个月的最后一天和上个月的前一天(2010年4月,我想显示股票)中拉出股票收盘价2010年4月30日和2010年3月31日收盘价

关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:0)

您可以使用窗口函数和条件聚合:

SELECT sd.*
FROM (SELECT sd.*, 
             ROW_NUMBER() OVER (PARTITION BY TickerSymbol, YEAR(TradeDate), MONTH(TradeDate)
                                ORDER BY TradeDate DESC) as seqnum
      FROM StockData sd
      WHERE TradeDate >= '2000-01-01' AND ST_Close IS NOT NULL
     ) sd
WHERE seqnum = 1
ORDER BY TradeDate, TickerSymbol;

这将从每个月的最后一条记录中获取所有信息。

按年度排序(TradeDate),MONTH(TradeDate),TickerSymbol;

答案 1 :(得分:0)

以下是一种方法,假设您需要的前一个收盘价值是自上个月上次交易的股票之日起。

WITH
    daily_close AS (
        SELECT  
            TradeDate
          , TickerSymbol
          , ST_Close
          , ROW_NUMBER() OVER(PARTITION BY TickerSymbol, EOMONTH(TradeDate) ORDER BY TradeDate DESC) AS day_num
        FROM    dbo.StockData
        WHERE   TradeDate >= '2012-01-01'
                AND ST_Close IS NOT NULL
    )
SELECT
        YEAR(curr.TradeDate) AS Year
      , MONTH(curr.TradeDate) AS Month
      , curr.TickerSymbol
      , curr.ST_Close AS CurrentMonthClose
      , prev.ST_Close AS PriorMonthClose
FROM daily_close AS curr
LEFT JOIN daily_close AS prev ON
            prev.TickerSymbol = curr.TickerSymbol
            AND prev.TradeDate < DATEADD(month, -1, DATEADD(day, 1, curr.TradeDate))
            AND prev.TradeDate >= DATEADD(month, -2, DATEADD(day, 1, curr.TradeDate))
            AND prev.day_num = 1
WHERE 
    curr.day_num = 1
ORDER BY
      Year
    , Month
    , TickerSymbol;