在過去的幾天中,此查詢一直讓我忙碌。我試圖用不同的想法重寫它,但我仍然有同樣的問題。爲了簡化問題,我將查詢的一部分放入視圖中,該視圖返回了23條記錄。使用左連接我想添加來自表tblDatPositionsCalc的字段到這23條記錄。正如你所看到的,我對tblDatPositionsCalc有一個額外的條件,以便只考慮最近的記錄。有了這個條件,它會返回21條記錄。連接應該在colAccount和colId的兩個字段上。SQL Server LEFT JOIN
我只是希望查詢從視圖中返回23條記錄,並儘可能從tblDatPositionsCalc獲取信息。實際上,在tblDatPositionsCalc中沒有相應的id和account的情況下,視圖中只有2條記錄,這意味着在23條記錄中,只有2條記錄會在來自表tblDatPositionsCalc的字段中缺少值。
我的查詢的問題是它只返回來自tblDatPositionsCalc的21條記錄。我不明白爲什麼。我試圖在加入條件之後立即移動條件,但這並沒有幫助。
SELECT TOP (100) PERCENT
dbo.vwCurrPos.Account,
dbo.vwCurrPos.Id,
dbo.vwCurrPos.TickerBB,
dbo.vwCurrPos.colEquityCode,
dbo.vwCurrPos.colType,
dbo.vwCurrPos.colCcy,
dbo.vwCurrPos.colRegion,
dbo.vwCurrPos.colExchange,
dbo.vwCurrPos.[Instr Type],
dbo.vwCurrPos.colMinLastDay,
dbo.vwCurrPos.colTimeShift,
dbo.vwCurrPos.Strike,
dbo.vwCurrPos.colMultiplier,
dbo.vwCurrPos.colBetaVol,
dbo.vwCurrPos.colBetaEq,
dbo.vwCurrPos.colBetaFloor,
dbo.vwCurrPos.colBetaCurv,
dbo.vwCurrPos.colUndlVol,
dbo.vwCurrPos.colUndlEq,
dbo.vwCurrPos.colUndlFut,
tblDatPositionsCalc_1.colLots,
dbo.vwCurrPos.[Open Positions],
dbo.vwCurrPos.colListMatShift,
dbo.vwCurrPos.colStartTime,
tblDatPositionsCalc_1.colPrice,
tblDatPositionsCalc_1.colMktPrice,
dbo.vwCurrPos.colProduct,
dbo.vwCurrPos.colCalendar,
CAST(dbo.vwCurrPos.colExpiry AS DATETIME) AS colExpiry,
dbo.vwCurrPos.colEndTime,
CAST(tblDatPositionsCalc_1.colDate AS datetime) AS colDate,
dbo.vwCurrPos.colFund,
dbo.vwCurrPos.colExchangeTT,
dbo.vwCurrPos.colUserTag
FROM dbo.vwCurrPos
LEFT OUTER JOIN dbo.tblDatPositionsCalc AS tblDatPositionsCalc_1
ON tblDatPositionsCalc_1.colId = dbo.vwCurrPos.Id
AND tblDatPositionsCalc_1.colAccount = dbo.vwCurrPos.Account
WHERE (tblDatPositionsCalc_1.colDate =
(SELECT MAX(colDate) AS Expr1 FROM dbo.tblDatPositionsCalc))
ORDER BY
dbo.vwCurrPos.Account,
dbo.vwCurrPos.Id,
dbo.vwCurrPos.colEquityCode,
dbo.vwCurrPos.colRegion
任何想法可能導致問題的原因是什麼?
嗯,首先你說'我有一個額外的條件在tblDatPositionsCalc爲了只考慮最近的記錄,然後你說'它只返回21條記錄'是不是你的where-clause過濾出你想要的?我理解正確嗎?然後將where條件移動到您的'LEFT OUTER JOIN'的附加'AND'中可以消除您的問題。 – DrCopyPaste 2014-10-02 10:02:44