Sunday, March 11, 2012

Double Left Join?

Helllo...

I need to do a query that left joins a table conditionally.

select t.*, v.vwap, a.moniker,v.dateTime
from accounts a, stocks s, trades t left join vwaps v on t.[date] = v.dateTime
where a.accountNumber = t.accountNumber AND t.symbol = s.symbol
AND a.moniker not like '%kb001%'
AND t.timeVWAP is not NULL
ORDER BY a.moniker, t.date, t.[transaction], t.symbol

but only left join vwaps if s.stockid = v.stockid

I used to have it like this.

select t.*, v.vwap, a.moniker,v.dateTime
from accounts a, trades t, stocks s left join vwaps v on s.stockID = v.stockID
where a.accountNumber = t.accountNumber AND t.symbol = s.symbol
AND a.moniker not like '%kb001%'
AND t.timeVWAP is not NULL
ORDER BY a.moniker, t.date, t.[transaction], t.symbol

in which case I would need to only join if v.dateTime = t.[date]
else just attach a NULL value.
Any idea how do to this?try this

select t.*, v.vwap, a.moniker,v.dateTime
from
accounts a,
(
stocks s
join
trades t
on t.symbol = s.symbol
)
left join
vwaps v on t.date = v.dateTime and s.stockid = v.stockid
where a.accountNumber = t.accountNumber
AND a.moniker not like '%kb001%'
AND t.timeVWAP is not NULL
ORDER BY a.moniker, t.date, t.transaction, t.symbol|||Will give it a try. Thanks.

No comments:

Post a Comment