在下面的查询中,我想从JOIN
语句中删除子查询(因为我的两个SELECT
语句正在从同一个表中选择数据)。我该如何使用该别名?在此先感谢您的帮助。
declare @StartDate datetime= '8/01/2011'
declare @EndDate datetime = '9/20/2011'
declare @PortfolioId int = 6
SELECT
Previous.PreviousNAV,
Todays.TodaysNAV,
ISNULL((Todays.TodaysNAV-Previous.PreviousNAV),0) NetChange,
ISNULL((Todays.TodaysNAV-Previous.PreviousNAV) / Todays.TodaysNAV,0) BAMLIndex
FROM
(
SELECT PortfolioId,ISNULL(NAV,0) PreviousNAV
FROM Fireball..NAV
WHERE Date BETWEEN @StartDate AND @EndDate and PortfolioId = @PortfolioId
) Previous
JOIN
(
SELECT PortfolioId,ISNULL(NAV,0) TodaysNAV
FROM Fireball..NAV
WHERE Date = @EndDate and PortfolioId = @PortfolioId
) Todays
ON Previous.PortfolioId = Todays.PortfolioId
答案 0 :(得分:2)
完全消除子查询。我不认为他们在查询中添加任何内容。试试这个:
SELECT
Previous.NAV as PreviousNAV,
Todays.NAV as TodaysNav,
ISNULL((Todays.NAV-Previous.NAV),0) NetChange,
ISNULL((Todays.NAV-Previous.NAV) / Todays.NAV,0) BAMLIndex
FROM
Fireball..NAV as Previous
JOIN
Fireball..NAV as Todays
ON Previous.portfolioID = Todays.PortfolioID
WHERE Previous.Date BETWEEN @StartDate AND @EndDate
AND Previous.PortfolioId = @PortfolioId
AND Todays.Date = @EndDate