SQL Server 2014查询以获取已关闭和打开的交易语句

时间:2016-08-15 08:20:17

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

我的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:使用上述条件输出以下格式的数据

  • 条件:
    1. 只应考虑每个卖出日期之后的第一个购买日期,并与特定股票的考虑购买日期之后的第一个卖出日期相匹配。
    2. 如果在买入之后有一个股票的买入条目,中间没有卖出条目,那么应该忽略。

预期结果:

Result Format

我尝试了以下查询,但是不符合上述条件。

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

有些人可以帮忙吗?如果需要更多信息,请通知我。

1 个答案:

答案 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