引用聚合列的MySQL别名

时间:2009-11-24 18:00:30

标签: sql mysql alias aggregation

跟进我的问题summarizing-two-conditions-on-the-same-sql-table,我添加了一个RATIO列,它只是一个SUM(...)列除以第二个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

像这样定义RATIO看起来很干净,但显然forbidden by SQL

为了使查询正常工作,我只复制了NON_BILLABLE和BILLABLE的CASE语句。

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

是否有更好,更清晰(非冗余)的方式来编写此查询?

1 个答案:

答案 0 :(得分:4)

使用:

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