如何仅选择每个库存具有最新日期的行

时间:2014-06-17 08:51:00

标签: sql

股票数据

ticker  date         open   high    low     close   volume
--------------------------------------------------------------
AAA     2014-06-16   0.9    0.9     0.89    0.895   542
AAA     2014-06-15   1.32   1.33    1.31    1.32    2792
AAA     2014-06-14   1.19   1.25    1.19    1.25    417
AAA     2014-06-13   0.715  0.715   0.705   0.71    36526

BBB     2014-06-16   0.9    0.9     0.89    0.895   542
BBB     2014-06-15   1.32   1.33    1.31    1.32    2792
BBB     2014-06-14   1.19   1.25    1.19    1.25    417
BBB     2014-06-13   0.715  0.715   0.705   0.71    36526

CCC     2014-06-16   0.9    0.9     0.89    0.895   542
CCC     2014-06-15   1.32   1.33    1.31    1.32    2792
CCC     2014-06-14   1.19   1.25    1.19    1.25    417
CCC     2014-06-13   0.715  0.715   0.705   0.71    36526

我想选择这样它只返回具有最新日期(动态)的行,每个股票的结果为2014-06-16

AAA     2014-06-16   0.9    0.9     0.89    0.895   542
BBB     2014-06-16   0.9    0.9     0.89    0.895   542
CCC     2014-06-16   0.9    0.9     0.89    0.895   542

5 个答案:

答案 0 :(得分:1)

select Stock_data.* 
from Stock_data inner join ( 
   select ticker, max(date) maxdate 
   from Stock_Data 
   group by ticker) maxdates 
on maxdates.maxdate=date 
and maxdates.ticker=Stock_data.ticker

答案 1 :(得分:0)

试试这个

SELECT T.ticker,T.date,T.open,T.high,T.low,T.close,T.volume
FROM Table1 T
     INNER JOIN (
           SELECT ticker,Max(date) as MaxDate
           FROM Table1
          GROUP BY ticker
                ) S ON S.ticker = T.ticker AND T.date = S.MaxDate

答案 2 :(得分:0)

可以使用如下查询:  select d.ticker, MAX(d.date) from stock_data d group by d.ticker

答案 3 :(得分:0)

尝试以下查询:

WITH TAB AS (
    SELECT
        TICKER,
        DAY,
        OPEN,
        HIGH,
        LOW,
        CLOSE,
        VOLUME, 
        RANK() OVER(PARTITION BY TICKER 
                          ORDER BY DAY DESC) AS RANKK
      FROM Stocks)
SELECT TICKER, DAY,   OPEN,    HIGH,     LOW,     CLOSE,     VOLUME
FROM TAB 
WHERE TAB.RANKK = 1

答案 4 :(得分:0)

使用自然联接可以解决问题:

select * from 
table_name 
natural join (select ticker, max(date) as date 
          from table_name
          group by ticker);