案例陈述 - 不是表达式错误的组

时间:2014-09-24 17:30:01

标签: sql oracle

我有以下查询:

SELECT EMP_CD,
 EMP_NUM,
 to_char(PAY_DT,'yyyymm') as PAY_month,
 MAX(BILL_FREQ) as BILLING_FREQUENCY,
 MAX(FXD_CHRG) as FIXED_CHARGE, 
 SUM(Pay_1)/SUM(Pay_2) AS DEPT_CHARGE, 
 SUM(Pay_1)/SUM(Pay_2) AS SUB_CHARGE, 
WHERE EMP_CD in ('HP','2000') 
AND CODE in ('X','Y','Z') 
GROUP BY EMP_CD, EMP_NUM, TO_CHAR(PAY_DT,'yyyymm');

现在,我想在(' Z')中找到代码的dept_charge(' X',' Y')和SUB_CHARGE 为此,我尝试了以下方法:

SELECT EMP_CD,
 EMP_NUM,
 to_char(PAY_DT,'yyyymm') as PAY_month,
 MAX(BILL_FREQ) as BILLING_FREQUENCY,
 MAX(FXD_CHRG) as FIXED_CHARGE, 
 CASE WHEN CODE in ('X','Y') then SUM(Pay_1)/SUM(Pay_2) ELSE 0 END AS DEPT_CHARGE, 
 CASE WHEN CODE in ('Z') then SUM(Pay_1)/SUM(Pay_2) ELSE 0 END AS SUB_CHARGE, 
WHERE EMP_CD in ('HP','2000') 
AND CODE in ('X','Y','Z') 
GROUP BY EMP_CD, EMP_NUM, TO_CHAR(PAY_DT,'yyyymm');

我收到的错误是“不是按表达式分组”。谁能告诉我我哪里做错了。另外,如果还有其他更好的方法,请建议我。

作为一个例子..

EMP_NUM CODE    PAY_MONTH   PAY_1   PAY_2
552343  X         201006    32.82   547
552343  X         201006    36.12   602
552343  X         201006    33.12   552
552343  X         201006    33      550
552343  X         201006    32.82   547

对于这个数据集,我必须得到0.06为dept_charge,0为sub_charge

1 个答案:

答案 0 :(得分:0)

一般方法是首先使用聚合函数。我使用子查询因子(with子句)在emp_cd,emp_num,pay_month,billing_frequency和fixed_charge级别聚合作为中间步骤:

       WITH ep AS
  (SELECT emp_cd,
    emp_num,
    TO_CHAR(pay_dt,'yyyymm') AS pay_month,
    code,
    MAX(bill_freq) AS billing_frequency,
    MAX(fxd_chrg)  AS fixed_charge,
    SUM( NVL(pay_1,0)) sum_pay1,
    SUM(NVL(pay_2, 0)) sum_pay2
  FROM emp_payments
  WHERE emp_cd IN ('HP','2000')
  AND code     IN ('X','Y','Z')
  GROUP BY emp_cd,
    emp_num,
    TO_CHAR(pay_dt,'yyyymm'),
    code
  )
SELECT emp_cd,
  emp_num,
  pay_month,
  billing_frequency,
  fixed_charge,
  SUM(
  CASE
    WHEN code IN ('X','Y')
    THEN sum_pay1
    ELSE 0
  END ) / SUM(
  CASE
    WHEN code IN ('X','Y')
    THEN sum_pay2
    ELSE 0
  END ) AS dept_charge,
  SUM(
  CASE
    WHEN code IN ('Z')
    THEN sum_pay1
    ELSE 0
  END ) / SUM(
  CASE
    WHEN code IN ('Z')
    THEN sum_pay2
    ELSE 0
  END ) AS sub_charge
FROM ep
GROUP BY emp_cd,
  emp_num,
  pay_month,
  billing_frequency,
  fixed_charge