[英]SQL join to get field name
我有以下查詢,我希望編寫一個聯接,以根據ID給我提供股票趨勢的方向。
stock_trends
------------
stock_id
trend_id
direction_id
timestamp
price
breakout_price
trend_direction
---------------
id
direction
select s.*, v.latest_trend_date,
dbo.GetStockAverageVolume(s.id, latest_trend_date, GETDATE())
as avg_volume from stocks s
join(select stock_id, MAX(timestamp)as latest_trend_date from stock_trends st
group by st.stock_id) v on v.stock_id = s.id
where
(select top 1 trend_id from stock_trends
where s.id = stock_trends.stock_id order by [timestamp] desc) =
@trend_id and s.market_id = @market_id
and dbo.GetStockAverageVolume(s.id, latest_trend_date, GETDATE()) > 300000
order by latest_trend_date desc
如何修改上述查詢以根據stock_trends表中的direction_id獲取趨勢的方向?
例如:
select s.*, v.latest_trend_date,
dbo.GetStockAverageVolume(s.id, latest_trend_date, GETDATE())
as avg_volume, **direction** from stock s
...
...
...
伙計,我不擅長加入!
非常感謝。
這應該可以,但是我認為您的查詢可以優化
select stock_id, td.direction, MAX(timestamp) as latest_trend_date
from stock_trends st
join trend_direction td on st.direction_id = td.id
group by st.stock_id, td.direction
是的,然后將v.direction添加到主列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.