获得第一笔交易和最后一笔交易的价格

时间:2018-01-01 15:31:19

标签: sql-server database

问题是关于每天获取第一笔交易的价格和公司的最后一笔交易,我可以在此代码中获得价格

select t.date,t.PriceofShare as 'opening price'
from Trans t, Session s,Orders o
where s.date=t.Sdate
and t.Sdate=o.Sdate
and o.Sdate=s.date
and o.SID='MSFT'

返回此

date               opening price 
16:00:00.0000000    4000000.00
09:00:00.0000000    300000.00 

但我不知道如何将第一个作为开盘价,最后一个作为我试过的最后价格

select t.date,t.PriceofShare as 'opening price'
from Trans t, Session s,Orders o
where s.date=t.Sdate
and t.Sdate=o.Sdate
and o.Sdate=s.date
and o.SID='MSFT'
and t.date=(select Min(date)
from Trans)
union
select t.date,t.PriceofShare as 'closing price'
from Trans t, Session s,Orders o
where s.date=t.Sdate
and t.Sdate=o.Sdate
and o.Sdate=s.date
and o.SID='MSFT'
and t.date=(select Max(date)
from Trans)

结果是

date               opening price  
16:00:00.0000000    4000000.00

请帮忙 我的急诊室错误可以发布我的急诊室吗?

3 个答案:

答案 0 :(得分:1)

不完全确定您希望该节目的开盘价和收盘价,但这应该会给您一个想法..

SELECT *
FROM   Session s
       INNER JOIN Orders o
               ON o.Sdate = s.date
       CROSS apply (SELECT TOP 1 t.PriceofShare, t.date
                    FROM   Trans t
                    WHERE  s.date = t.Sdate
                           AND t.Sdate = o.Sdate
                    ORDER  BY t.date) o (OpeningPrice, OpeningPriceDate)
       CROSS apply (SELECT TOP 1 t.PriceofShare, t.date
                    FROM   Trans t
                    WHERE  s.date = t.Sdate
                           AND t.Sdate = o.Sdate
                    ORDER  BY t.date DESC) c (ClosingPrice, ClosingPriceDate)
WHERE  o.SID = 'MSFT' 

开始使用INNER JOIN语法加入表而不是旧式逗号分隔连接。这是一篇关于这个Bad habits to kick : using old-style JOINs

的好文章

答案 1 :(得分:0)

为什么你甚至需要会话?
使用它。

select * 
from ( select t.date, t.PriceofShare as 'price'
            , row_number() over (partition by CONVERT(date, t.Sdate) order by t.date desc) as open  
            , row_number() over (partition by CONVERT(date, t.Sdate) order by t.date asc)  as close 
         from Trans t  
         join Orders o
           on o.Sdate = t.Sdate
          and o.SID   = 'MSFT'  
) tt
where tt.open = 1 or tt.close = 1 
order by t.date

答案 2 :(得分:0)

刚看到这个问题。您可以使用 windows 函数 first_value 和 last_value。

select 
first_value(PriceofShare) over(order by t.date) as first_value,
last_value(PriceofShare) over(order by t.date) as last_value
from Trans t, Session s,Orders o
where s.date=t.Sdate
and t.Sdate=o.Sdate
and o.Sdate=s.date
and o.SID='MSFT'