2012-11-21 44 views
1

我創建了一個查詢,我想結果看起來像如下空:返回數據,如果數據不存在 - 用數據填充

Reporting Date Fund AssetClass % 
31/10/2012  1  Equity  10 
31/10/2012  1  Bond   40 
31/10/2012  1  Cash   40 
31/10/2012  1  Balanced  10 
31/10/2012  1  Other   0 

我上面有我的問題是,其中%是0,顯然沒有數據顯示。不過,我希望它顯示。

所以我認爲最好的解決方案是創建一個包含所有資產類的臨時表,然後從我的工作表中選擇右外部連接,以便填充沒有數據的行。代碼如下:

SELECT 
    ReportingDate 
, PortfolioID 
, AC.AssetClass 
, ROW_NUMBER() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC) AS [Rank] 
, CAST(SUM(Percentage) AS DECIMAL(22,1)) AS [Weight] 

FROM @Worktable as WT 

RIGHT OUTER JOIN @AssetClass AS AC 
    ON WT.AssetClass = AC.AssetClass 

GROUP BY WT.ReportingDate, WT.PortfolioID, AC.AssetClass 

ORDER BY [Weight] DESC 

我的問題是,當它返回它看起來像這樣:

Reporting Date Fund AssetClass % 
31/10/2012  1  Equity  10 
31/10/2012  1  Bond   40 
31/10/2012  1  Cash   40 
31/10/2012  1  Balanced  10 
NULL    NULL Other   NULL 

我怎麼能填充NULL的數據在此腳本?有沒有更好的方法可以做到這一點?

+0

難道你不只是在select查詢中使用ISNULL嗎?例如ISNULL(PortfolioID,0) – Ric

+0

感謝您的迴應。我試過了,它不起作用 –

+0

當你使用它時會發生什麼? – Ric

回答

1
SELECT 
    CASE WHEN Reporting IS NULL THEN MAX(Reporting) OVER (PARTITION BY (SELECT 1)) ELSE Reporting END AS Reporting 
, CASE WHEN Fund IS NULL THEN MAX(Fund) OVER (PARTITION BY (SELECT 1)) ELSE Fund END AS Fund 
, PortfolioID 
, AC.AssetClass 
, ROW_NUMBER() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC) AS [Rank] 
, CAST(SUM(ISNULL(Percentage, 0)) AS DECIMAL(22,1)) AS [Weight] 
FROM @Worktable as WT 
RIGHT OUTER JOIN @AssetClass AS AC 
    ON WT.AssetClass = AC.AssetClass 
GROUP BY WT.ReportingDate, WT.PortfolioID, AC.AssetClass 
ORDER BY [Weight] DESC 
+1

完美無缺的工作。非常感謝您的幫助 –

+0

不客氣...不要害羞回答良好的答案 –