2017-03-01 4 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 

は、どのように私は、状況> 1 <または> 2 <がTotalNotDespatchedとステータスが= 3であるすべてのsiteordersの数を返しますTotalInErrorの7と8?

+0

どのSQLの実装で作業していますか? – WilliamD

答えて

1

条件付き集計を使用します。 。 。 casesum()

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; 

私はあなたの最初の2つの値は、あなたが望むものであることを疑います。 TotalOrdersおよびTotalParcelsは、一般に同じ値を有する。どうして? COUNT()は、NULLの値を数えず、idは通常NULLではありません。

関連する問題