可以在子查询中使用SELECT Column值吗?

时间:2014-11-20 18:35:42

标签: sql-server

是否可以在UsageCounts Select()查询中使用HeaderID值?

    SELECT HeaderID, HeaderName, HeaderFileName, CreatedDate, UsageCounts = (

        SELECT 
    COUNT(ClassXML.value('(/Data/prpID)[1]', 'INT'))
    FROM CustomContent 
    WHERE ClassXML.value('(/Data/prpID)[1]', 'INT') = HeaderID

)
 FROM Headers

这是SQL Server 2008 R2

更新:我想我得到了一个结果集......它只花了8分钟。有什么改进吗?

2 个答案:

答案 0 :(得分:4)

提供Alias name并在correlated Subquery内使用。

SELECT HeaderID,
       HeaderName,
       HeaderFileName,
       CreatedDate,
       UsageCounts =(SELECT Count(ClassXML.value('(/Data/prpID)[1]', 'INT'))
                      FROM   CustomContent A
                      WHERE  ClassXML.value('(/Data/prpID)[1]', 'INT') = H.HeaderID) 
FROM   Headers H

答案 1 :(得分:1)

您可以尝试连接而不是子查询来加快速度。像这样:

Select 
    HeaderID,  
    max(HeaderName) HeaderName,  
    max(HeaderFileName) HeaderFileName,  
    max(CreatedDate) CreatedDate,  
    COUNT(ClassXML.value('(/Data/prpID)[1]', 'INT')) UsageCounts  
From Headers  
Left Join CustomContent on  
     ClassXML.value('(/Data/prpID)[1]', 'INT') = HeaderID  
Group by  
    HeaderID  

注意:我假设您只有1个HeaderName,HeaderFileName并为每个HeaderID创建