views:

163

answers:

1

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
FROM TRANSACTIONS
GROUP BY COMPANY_ID

Is there a better, cleaner (non-redundant) way to write this query?

+4  A: 

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
OMG Ponies