I have a query like this:
select
case when sp.provider='prv1' and sp.status_code = 404 then 'failed'
when sp.provider='prv1' and sp.status_code = 200 then 'success'
when time_taken is null or sp.status_code in (503) or sp.status_code is null then 'unavailable'
else 'other'
end as result,
count(*)
from services_serviceprofile sp
where
service_type = 'type1' and
sp.provider = 'prv1' and
sp.start_time >= '2022-08-22 00:00'
group by
case when sp.provider='prv1' and sp.status_code = 404 then 'failed'
when sp.provider='prv1' and sp.status_code = 200 then 'success'
when time_taken is null or sp.status_code = 503 or sp.status_code is null then 'unavailable'
else 'other'
end
order by count(*) desc;
How can I add a row for ‘all’ requests in CASES? If we add a when sp.provider='prv1'
with no more detailed condition then all cases become one ‘all’ case because and other cases are ignored.
2
Answers
You can’t do that inside the
CASE
, as it behaves like a series of IF.You need to compute the total separately and append it using
UNION
or delegate the total calculation to whatever tool uses those data.If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function for add last row total: