开发者

Referencing MySQL Alias of Aggregate Column

开发者 https://www.devze.com 2022-12-12 15:25 出处:网络
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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消