2014-01-06 62 views
0

我有一個景觀改造這個查詢:傳播其中,在查看條款子查詢

SELECT col1, 
     CONVERT(decimal(5, 4), SUM(Volume)/CONVERT(float, (
             SELECT SUM(Volume) 
             FROM A INNER JOIN B ON [..] 
             WHERE A.CodA = @param1 AND CodB.[Year] = @param2)) 
     ) AS [VolPercent] 
FROM A INNER JOIN B ON [..] 
WHERE A.CodA = @param1 AND CodB.[Year] = @param2 

所以,我有從外部查詢相同clausule來篩選子查詢。
什麼會是這樣的:

SELECT col1, 
     CONVERT(decimal(5, 4), SUM(Volume)/CONVERT(float, (
             SELECT SUM(Volume) 
             FROM A as C INNER JOIN B as D ON [..] 
             WHERE C.CodA = A.CodA AND D.[Year] = B.[Year])) 
     ) AS [VolPercent] 
FROM A INNER JOIN B ON [..] 

我怎麼能這樣做?有沒有辦法?

回答

1

在沒有WHERE的情況下創建一個視圖,然後使用WHERE子句查詢視圖應該給出完全相同的結果和完全相同的性能。但是,您需要添加將在where子句中使用的列。所以,是的,創建視圖

create view MyView as 
SELECT ACod.A, CodB.[Year], 
     col1, 
     CONVERT(decimal(5, 4), SUM(Volume)/CONVERT(float, (
             SELECT SUM(Volume) 
             FROM A as C INNER JOIN B as D ON [..] 
             WHERE C.CodA = A.CodA AND D.[Year] = B.[Year])) 
     ) AS [VolPercent] 
FROM A INNER JOIN B ON [..] 

,然後你的查詢是:

select * from MyView 
where A = whatever 
and [Year] = whatever 

乾杯 -

+0

哦,不!我在SELECT中忘記了CodA,Year列!當然! :) –

+1

沒問題:)。祝你好運! –