簡體   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