在SQL Server 2000 Ms中,子查询运行缓慢的SQL计数

时间:2016-03-10 09:27:06

标签: sql-server

我使用count语句进行SQL查询,并包含2个表之间的左连接。

但是,查询运行速度很慢,每个查询的结果显示为5-10分钟。

希望任何人都可以通过我正在处理的以下查询来帮助提高性能。

    select origin,count(*) as shipmentcount,
    (select count(*) as unprocessed  from tblshipmentdetail sd
    left join tblshipmentprocess sp on 
    sd.airbillno=sp.airbillno 
    where sp.airbillno is null and 
    sd.pickupdate >='2016-01-01' and sd.pickupdate <='2016-01-31'
    and sd.origin=a.origin
    ) as unprocessed
    from tblshipmentdetail a
    where pickupdate >='2016-01-01' and pickupdate <='2016-01-31'
    group by origin

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合而不是相关查询:

    select origin,count(*) as shipmentcount,
           count(case when sp.airbillno is null then 1 end) as unprocessed
    from tblshipmentdetail a
    LEFT OUTER JOIN tblshipmentprocess sp
     ON(a.airbillno=sp.airbillno)
    where a.pickupdate >='2016-01-01' and a.pickupdate <='2016-01-31'
    group by a.origin

答案 1 :(得分:1)

请试试这个,这可能会对你有所帮助

select origin,SUM(1) as shipmentcount,SUM(CASE WHEN sp.airbillno is NULL THEN 1 ELSE 0 END ) unprocessed
from tblshipmentdetail sd
left join tblshipmentprocess sp on  sd.airbillno=sp.airbillno 
where pickupdate >='2016-01-01' and pickupdate <='2016-01-31'
group by origin