Following my summarizing-two-conditions-on-the-same-sql-table question, I added a RATIO column, which is just one SUM (...) column divided by a second SUM (...):
SELECT
COMPANY_ID,
SUM(CASE WHEN STATUS IN (0, 1) THEN 1 ELSE 0 END) AS NON_BILLABLE,
SUM(CASE WHEN STATUS IN (2, 3) THEN 1 ELSE 0 END) AS BILLABLE
SUM(NON_BILLABLE)/SUM(BILLABLE) AS RATIO
FROM TRANSACTIONS
GROUP BY COMPANY_ID
It looks nice and clean to define a RATIO like this, but SQL is also apparently forbidden .
To make the query work, I simply copied the CASE statements for NON_BILLABLE and BILLABLE.
SELECT
COMPANY_ID,
SUM(CASE WHEN STATUS IN (0, 1) THEN 1 ELSE 0 END) AS NON_BILLABLE,
SUM(CASE WHEN STATUS IN (2, 3) THEN 1 ELSE 0 END) AS BILLABLE
SUM(CASE WHEN STATUS IN (0, 1) THEN 1 ELSE 0 END)/SUM(CASE WHEN STATUS IN (2, 3) THEN 1 ELSE 0 END) AS RATIO
FROM TRANSACTIONS
GROUP BY COMPANY_ID
Is there a better, cleaner (not redundant) way to write this query?
source
share