繁体   English   中英

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

[英]get the price of the first transaction and last transaction

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

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

请帮助我的急诊室可能错了我可以发布我的急诊室吗?

不完全确定您希望如何显示开盘价和收盘价,但这应该给您一个想法..

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语法来连接表,而不是旧样式的逗号分隔连接。 这里有一篇关于这个坏习惯的好文章:使用旧式 JOIN

为什么你甚至需要会话?
处理这个。

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

刚看到这个问题。 您可以使用 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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM