2012-07-26 63 views
2

有沒有辦法將值傳遞給派生表查詢?傳遞值派生表

在派生表中,我想從外部查詢中引用一個值([docSVsys].[sID])

我得到一個錯誤:

Msg 4104, Level 16, State 1, Line 7 The multi-part identifier "docSVsys.sID" could not be bound.

是的,我知道這個查詢可以簡化爲不循環。
讓遊標必須循環並嘗試將其轉換爲如此設置。

select top 10 [docSVsys].[sID], [sI].[count] 
from docSVsys 
join 
(
    select count(*) as [count] 
    from docSVenum1 as [sIt] 
    where [sIt].[sID] = [docSVsys].[sID] 
) as [sI] 
on '1' = '1' 
order by [docSVsys].[sID] 

交叉應用似乎在伎倆。 而且它比遊標版本快三分之一。 使用交叉的真正查詢適用於下面。

SELECT [sO].[sID], [sI].[max], [sI].[avg], [sI].[stdev] 
FROM docSVsys as [sO] with (nolock) 
cross apply 
( 
    select [sO].[sID], max(list.match) as 'max', avg(list.match) as 'avg', stdev(list.match) as 'stdev' 
    from 
    (
     select #SampleSet.[sID], [match] = 200 * count(*)/CAST (#SampleSetSummary.[count] + [sO].[textUniqueWordCount] as numeric(8,0)) 
     from #SampleSet with (nolock) 
     join FTSindexWordOnce as [match] with (nolock) -- this is current @sID 
      on match.wordID = #SampleSet.wordID 
      and [match].[sID] = [sO].[sID] 
     join #SampleSetSummary with (nolock) -- to get the word count from the sample set 
      on #SampleSetSummary.[sID] = #SampleSet.[sID] 
     group by #SampleSet.[sID], #SampleSetSummary.[count] 
    ) as list 
    having max(list.match) > 60 
) as [sI] 
where [textUniqueWordCount] is not null and [textUniqueWordCount] > 4 and [sO].[sID] <= 10686 
order by [sO].[sID] 

回答

3

你可以做你想做的與CROSS APPLY而不是JOIN:

select top 10 [docSVsys].[sID], [sI].[count] 
from docSVsys 
cross apply 
( 
    select count(*) as [count]  
    from docSVenum1 as [sIt] 
    where [sIt].[sID] = [docSVsys].[sID] 
) as [sI] 
order by [docSVsys].[sID] 
+0

這將像一個循環。對? – 2012-07-26 21:03:11

+0

讓我測試一下。到目前爲止它看起來不錯。 – Paparazzi 2012-07-26 21:15:17

+0

是的,它是以循環的方式實現的,但那是被要求的。它是否比通過查詢進行的連接更好地執行取決於表的大小,索引等。另一個選項可能是通過將查詢執行到臨時表中,以便可以在sID上創建索引。我會說測試各種選項,並使用最好的。 – GilM 2012-07-26 21:30:33

2

的ID添加到派生表,並加入對:

select top 10 [docSVsys].[sID], [sI].[count] 
from docSVsys 
join 
(
    select [sIt].[sID], count(*) as [count] 
    from docSVenum1 as [sIt] 
    group by [sIt].[sID] 
) as [sI] 
on [sI].[sID] = [docSVsys].[sID] 
order by [docSVsys].[sID] 
+0

是的,這是備用語法。但我絕對必須一次循環一個[docSVsys]。[sID]。在現實生活中,如果內部循環產生了所有的行,那麼它將是幾個TB。該內部循環每次計算大約1M行以生成一個輸出行。內循環被稱爲約1M次。這可能只是留在遊標中。作爲一個遊標,它運行8小時(內存佔用量小)。 – Paparazzi 2012-07-26 21:10:49