Following up on my question summarizing-two-conditions-on-the-same-sql-table, I added a RATIO column that is simply one SUM(...) column divided by a second SUM(...) column:
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 the RATIO like that, but also apparently forbidden by SQL.
To get the query working, I just 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
F开发者_JS百科ROM TRANSACTIONS
GROUP BY COMPANY_ID
Is there a better, cleaner (non-redundant) way to write this query?
Use:
SELECT x.company_id,
x.non_billable,
x.billable,
x.non_billable/x.billable AS RATIO
FROM (SELECT t.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
FROM TRANSACTIONS
GROUP BY t.company_id) x
精彩评论