2012-04-02 110 views
0

我有以下查詢,我正在尋找一個連接,以給我一個基於id的股票趨勢的方向。SQL加入以獲取字段名稱

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 
... 
... 
... 

人我在加入壞了!

非常感謝。

+0

你正在使用哪種SQL? – Hogan 2012-04-02 04:05:22

+0

@Hogan MSSQL 2008 – robson 2012-04-02 04:06:54

回答

0

這應該工作,但是我覺得你的查詢可以優化

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到主列表。

+0

感謝@Hogan,這不是我正在尋找的。我試圖在我的子查詢中添加方向標識並將其添加到我的組中,但它更改了我的結果集。我可以在direction_id上進行連接而不必將其添加到GROUP BY中嗎? – robson 2012-04-02 04:17:04

+0

@robokop - 它不應該改變結果集...查詢必須看起來不同於你發佈的內容。 – Hogan 2012-04-02 10:13:19

+0

@robokop - 或者你的一些direction_id字段爲空。你檢查了嗎? – Hogan 2012-04-02 10:44:38