2017-03-01 61 views
0

我有3个表ImportRecord,SiteOrder和Parcel其中ImportRecord.ID = SiteOrder.ImportId和SiteOrder.ID = Parcel.SiteOrderId。从子查询获得计数

我需要一个查询检索以下:

declare @Started as varchar(50) = null 
declare @Ended as varchar(50) = null 
declare @ClientCode as varchar(50) = null 
declare @FileName as varchar(50) = null 
declare @PageSize as int = null 

select Count(so.ID) as TotalOrders, Count(p.ID) as TotalParcels,    
     --Count(so.Status <> 1 or so.Status <> 2) as TotalNotDespatched, 
     --Count(so.Status = 3 or so.Status = 8 or so.Status = 7) as TotalInError,   
     ir.ID, ir.Filename, ir.Started, ir.Status, ir.ClientCode 
from ImportRecord ir with (nolock) 
join SiteOrder so with (nolock) 
    on so.ImportId = ir.ID 
join Parcel p with (nolock) 
    on p.SiteOrderId = so.ID 
where 1=1 
    and ir.Status <> 5 --NOT DELETED 
    and (@ClientCode is null or ir.ClientCode = @ClientCode) 
    and (@Started is null or ir.Started = @Started) 
    and (@Ended is null or ir.Ended = @Ended) 
    and (@ClientCode is null or ir.ClientCode = @ClientCode) 
    and (@FileName is null or ir.Filename like '%' + @FileName + '%') 
group by ir.ID, ir.Filename, ir.Started, ir.Status, ir.ClientCode 
order by ir.ID desc 

如何返回所有siteorders的计数,其中状态<> 1或<> 2这是TotalNotDespatched并且其中状态= 3, 7和8的TotalInError?

+0

您正在使用哪种SQL实现? – WilliamD

回答

1

使用条件聚合。 。 。 sum()case

select Count(so.ID) as TotalOrders, Count(p.ID) as TotalParcels,    
     sum(case when so.Status not in (1, 2) then 1 else 0 end) as TotalNotDespatched, 
     sum(case when so.Status in (3, 7, 8) then 1 else 0 end) as TotalInError,   
     ir.ID, ir.Filename, ir.Started, ir.Status, ir.ClientCode 
from ImportRecord ir with (nolock) join 
    SiteOrder so with (nolock) 
    on so.ImportId = ir.ID join 
    Parcel p with (nolock) 
    on p.SiteOrderId = so.ID 
where 1=1 
     ir.Status <> 5 --NOT DELETED and 
     (@ClientCode is null or ir.ClientCode = @ClientCode) and 
     (@Started is null or ir.Started = @Started) and 
     (@Ended is null or ir.Ended = @Ended) and 
     (@ClientCode is null or ir.ClientCode = @ClientCode) and 
     (@FileName is null or ir.Filename like '%' + @FileName + '%') 
group by ir.ID, ir.Filename, ir.Started, ir.Status, ir.ClientCode 
order by ir.ID desc; 

我怀疑你的前两个值是你想要什么。 TotalOrdersTotalParcels通常具有相同的值。为什么? COUNT()计算非NULL值的数量,而id通常不是NULL