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

问题描述 投票:0回答:2

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

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

请帮助我的ER可能错了我可以发布我的ER吗?

sql-server database
2个回答
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的好文章


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
© www.soinside.com 2019 - 2024. All rights reserved.