Summing two conditions in the same SQL table

Given SQL table

Transactions ID INT COMPANY_ID INT STATUS INT 

where STATUS IN (0,1) indicates a free transaction, and STATUS IN (2,3) indicates a paid transaction, which simply (I hope) the ANSI SQL statement will show me, for COMPANY_ID , the number of paid transactions, non-paid transactions and their attitude?

A concept product in the right direction is good, if not a specific operator. My first attempts were to join the table with the WHERE clauses for the two status groups myself, but I was stuck on how to get a column representing each individual score so that I could calculate the coefficient.

This is conceptually very similar to summarize-aggregated-data , but I'm not sure how to extend this question to this.

+4
source share
1 answer

Here is the beginning, I think it’s on the right line ... It remains only to add the ratio.

 SELECT COMPANY_ID, NON_BILLABLE = SUM(CASE STATUS WHEN IN (0, 1) THEN 1 ELSE 0 END), BILLABLE = SUM(CASE STATUS WHEN IN (2, 3) THEN 1 ELSE 0 END) FROM TRANSACTIONS GROUP BY COMPANY_ID 

EDIT: for compliance with standards.

 SELECT COMPANY_ID, SUM(CASE STATUS WHEN IN (0, 1) THEN 1 ELSE 0 END) AS NON_BILLABLE, SUM(CASE STATUS WHEN IN (2, 3) THEN 1 ELSE 0 END) AS BILLABLE FROM TRANSACTIONS GROUP BY COMPANY_ID 
+5
source

All Articles