我的SQL Server 2014中有一个表:
CREATE TABLE [dbo].[tblTradeSuggestions]
(
[StockId] [bigint] NOT NULL,
[DateGreg] [bigint] NOT NULL, -- Date Stored as yyyymmdd
[TradeSuggestion] [nvarchar](50) NOT NULL,
[ClosePrice] [real] NOT NULL
) ON [PRIMARY]
DCL&可以从https://1drv.ms/u/s!An7s9XmnfXFdg6dVEgS9-msdkk9GUg
下载上表的DML脚本现在我需要两个查询(a& b),如下所示:
查询1:使用上述条件输出以下格式的数据
预期结果:
我尝试了以下查询,但是不符合上述条件。
SELECT
ts1.StockId, ts1.DateGreg as BuyDate, ts1.ClosePrice AS BuyPrice,
ts2.DateGreg AS SellDate, ts2.ClosePrice AS SellPrice,
ts2.ClosePrice - ts1.ClosePrice AS Diff
FROM
tblTradeSuggestions ts1
JOIN
tblTradeSuggestions ts2 ON ts1.StockID = ts2.StockID AND ts1.DateGreg < ts2.DateGreg
WHERE
ts1.TradeSuggestion = 'Buy' AND ts2.TradeSuggestion = 'Sell'
ORDER BY
ts1.StockId, ts1.DateGreg
查询2:购买日期后的购买日期和没有卖出日期的股票清单,采用以下格式。
StockId DateGreg TradeSuggestion ClosePrice
----------------------------------------------
4583 20150901 Buy 46.45
有些人可以帮忙吗?如果需要更多信息,请通知我。
答案 0 :(得分:1)
试试这个
顺便说一下,你的解释似乎建议一对一,但你的结果似乎表明你想要将1买入映射到许多销售,如果你买,卖,卖,然后买,卖,卖? SELECT
ts1.StockId, ts1.DateGreg as BuyDate, ts1.ClosePrice AS BuyPrice,
ts2.DateGreg AS SellDate, ts2.ClosePrice AS SellPrice,
ts2.ClosePrice - ts1.ClosePrice AS Diff
FROM
tblTradeSuggestions ts1
CROSS APPLY
(SELECT TOP 1 * FROM tblTradeSuggestions ts3 WHERE
ts1.StockID = ts3.StockID AND
ts1.DateGreg < ts3.DateGreg AND
ts3.TradeSuggestion = 'Sell'
ORDER BY ts3.DateGreg) Ts2
WHERE
ts1.TradeSuggestion = 'Buy'
ORDER BY
ts1.StockId, ts1.DateGreg
获取不匹配的购买
SELECT ts1.StockId, ts1.DateGreg, ts1.TradeSuggestion, ts1.ClosePrice
FROM tblTradeSuggestions ts1
LEFT JOIN
tblTradeSuggestions ts2
ON
ts1.StockID = ts2.StockID AND
ts1.DateGreg < ts2.DateGreg AND
ts2.TradeSuggestion = 'Sell'
WHERE ts1.TradeSuggestion = 'Buy' AND ts2.StockId IS NULL