I have 3 tables ImportRecord, SiteOrder and Parcel where ImportRecord.ID=SiteOrder.ImportId and SiteOrder.ID=Parcel.SiteOrderId.
I need a query to retrieve the following:
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
How do I return a count of all siteorders where the status <>1 or <>2 which are the TotalNotDespatched and where the status = 3, 7 and 8 for TotalInError?
Use conditional aggregation . . . sum()
with 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;
I doubt that your first two values are what you want. TotalOrders
and TotalParcels
will generally have the same value. Why? COUNT()
counts the number of non- NULL
values, and id
s are usually not NULL
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.