3

有没有办法将值传递给派生表查询?

在派生表中,我想([docSVsys].[sID])从外部查询中引用一个值。

我收到一个错误:

消息 4104,级别 16,状态 1,第 7 行 无法绑定多部分标识符“docSVsys.sID”。

是的,我知道这个查询可以简化为无循环。
有一个游标必须循环并尝试将其转换为如此设置。

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]

交叉应用似乎可以解决问题。它比游标版本快 1/3。下面使用交叉应用的真实查询。

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]
4

2 回答 2

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] 
于 2012-07-26T20:46:33.190 回答
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]
于 2012-07-26T20:32:41.363 回答