我在SQL Server 2012 DB中有以下数据表:
DATE TICKER PRICE
2015-09-25 A 10
2015-09-24 A 9
2015-09-23 A 8
2015-09-25 B 3
2015-09-24 B 4
2015-09-23 B 5
我想用sql查询选择以下值:
TICKER VALUE
A 1.25
B 0.6
如果股票代码A的值为10/8(最新日期和特定日期,在此示例中为2015-09-23且应该可更改)。
股票代码B的值为3/5。
这就是我的尝试:
SELECT DISTINCT TICKER,
ROUND(
((SELECT PRICE FROM INDICEPRICEHISTORY WHERE TICKER = 'A' AND EOD = '2015-09-25') /
(SELECT PRICE FROM INDICEPRICEHISTORY WHERE TICKER = 'A' AND EOD = '2015-09-23')),2)
AS VALUE
FROM INDICEPRICEHISTORY
所以我至少需要做的是获得WHERE TICKER =' A'相对于所选的实际股票代码而言......并且EOD' s(EOD = DATE)是可变的..
提前谢谢。
答案 0 :(得分:0)
您可以使用CTE获取最后的价格,在您查找的日期加入价格:
;WITH
LastPrice
(
SELECT Ticker, Price,
RowNumber = ROW_NUMBER() OVER (PARTITION BY Ticker ORDER BY EOD DESC)
FROM INDICEPRICEHISTORY
)
SELECT I.Ticker,
Value = L.Price / I.Price
FROM INDICEPRICEHISTORY I
INNER JOIN LastPrice L ON I.Ticker = L.Ticker
WHERE I.EOD = '2015-09-23' AND L.RowNumber = 1
答案 1 :(得分:0)
您可以使用first_value
和last_value
分别获取每个跟踪器的第一个和最后一个价格。从那以后,它只是数学:
SELECT DISTINCT [tracker],
LAST_VALUE([price]) OVER (PARTITION BY [tracker]
ORDER BY [date]
ROWS BETWEEN UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING) /
FIRST_VALUE([price]) OVER (PARTITION BY [tracker]
ORDER BY [date]
ROWS BETWEEN UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING)
AS [Growth]
FROM mytable
<强> SQLFiddle 强>