从子查询中获取计数

时间:2017-03-01 11:17:02

标签: mysql sql

我有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

如何返回状态&lt;&gt; 1或&lt;&gt; 2为TotalNotDespatched且状态= 3,7和8为TotalInError的所有会员的计数?

1 个答案:

答案 0 :(得分: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