snippetsqlMajor
How to get count for different columns on same table
Viewed 0 times
samecolumnsdifferentgetforhowcounttable
Problem
Table #01
Table #02
Expected Result:
How do I need to write the query so that I could get the result as expected?
Status:StatusID Status
-----------------------
1 Opened
2 Closed
3 ReOpened
4 PendingTable #02
Claims:ClaimID CompanyName StatusID
--------------------------------------
1 ABC 1
2 ABC 1
3 ABC 2
4 ABC 4
5 XYZ 1
6 XYZ 1Expected Result:
CompanyName TotalOpenClaims TotalClosedClaims TotalReOpenedClaims TotalPendingClaims
--------------------------------------------------------------------------------
ABC 2 1 0 1
XYZ 2 0 0 0How do I need to write the query so that I could get the result as expected?
Solution
It's easiest with
SUM() and a CASE statement:select CompanyName,
sum(case when StatusID=1 then 1 else 0 end) as TotalOpenClaims,
sum(case when StatusID=2 then 1 else 0 end) as TotalClosedClaims,
sum(case when StatusID=3 then 1 else 0 end) as TotalReOpenedClaims,
sum(case when StatusID=4 then 1 else 0 end) as TotalPendingClaims
from Claims
group by CompanyName;Code Snippets
select CompanyName,
sum(case when StatusID=1 then 1 else 0 end) as TotalOpenClaims,
sum(case when StatusID=2 then 1 else 0 end) as TotalClosedClaims,
sum(case when StatusID=3 then 1 else 0 end) as TotalReOpenedClaims,
sum(case when StatusID=4 then 1 else 0 end) as TotalPendingClaims
from Claims
group by CompanyName;Context
StackExchange Database Administrators Q#163448, answer score: 29
Revisions (0)
No revisions yet.