4

跟进我的问题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 看起来很干净,但显然也被 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

是否有更好、更简洁(非冗余)的方式来编写此查询?

4

1 回答 1

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
于 2009-11-24T18:05:41.593 回答