避免SQL select语句中重复子查询的最佳方法

时间:2019-06-20 11:12:59

标签: sql sql-server tsql stored-procedures

我正在使用SQL存储过程从数据库中检索数据。由于我正在使用多个子查询,因此查询速度非常慢,请提出重写以下查询的最佳方法,以避免出现子查询。

    Select Companyid, 
           companyname, 
          (select count(distinct Identifier.SID) 
                  from CompaniesUsers   
                  join Identifier on CompaniesUsers.UniqueId = Identifier.UniqueId  
                 where Companies.CompanyId = CompaniesUsers.CompanyId 
                 and CompaniesUsers.IsActive = 1 
                 and Identifier.IsActive = 1 ) as CustomerCount,
         (select count(distinct CompaniesUsers.UniqueId) 
                 from CompaniesUsers    
                 where Companies.CompanyId = CompaniesUsers.CompanyId    
                 and CompaniesUsers.IsActive = 1 
                 and CompaniesUsers.UniqueId != '-'     )
         -      (Same query used in the CustomerCount) as AnonymousCustomerCount        
         from Companies where Companies.isactive = 1

在这里,我想为AnonymousCustomerCount重用客户计数查询。最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

尝试外部申请并查看它是否对您有效:

Select Companyid,
companyname,
CustomerCount.Count,
TotalCount.Total - CustomerCount.Count as AnonymousCustomerCount
from CompanyTable
OUTER APPLY (
select Count
  joining of 2 tables
) AS CustomerCount
OUTER APPLY (
  Subquery Total to get total count by joining 2 tables
) AS TotalCount

答案 1 :(得分:1)

您应该能够使用公用表表达式来使查询更易于阅读:

with 
 customer_count as 
   (select query with joining of 2 tables), 
 user_count as
   (Subquery to get total count by joining 2 tables)

Select Companyid,
companyname,
customer_count.column_name, 
customer_count.column_name - user_count.column_name
from CompanyTable
join customer_count on ?
join user_count on ?

虽然不确定这会提高性能...