是否可以在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分钟。有什么改进吗?
答案 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创建