在Oracle

时间:2018-02-20 21:16:37

标签: sql oracle group-by substr regexp-substr

以下是一个示例查询:

select acct_no, month, sum(amount), substr(charge_type, 1, 3),
       case when (charge_type in ('CRE1', 'CRE2')
            then 'electronic payment'
            else 'cash'
       end as 'payment_type'
from   billing_data
where  charge_type in ('CRE1', 'CRE2', 'CASH')
group  by acct_no, month, sum(amount), 
          substr(charge_type, 1, 3)
having sum(amount) != 0
order  by acct_no asc;

我想要实现的是返回每个帐号组合在一起的CRE1和CRE2费用类型金额的总和,其中该总和不是0.

如果没有group by中的substr,查询将运行并返回预期结果之外,CRE1和CRE2费用类型不会在一行中汇总。

当我在group by中添加substr时,我收到以下错误消息:

[Error] Execution (63: 15): ORA-00979: not a GROUP BY expression

有没有办法在Oracle中实现这一目标?

编辑:对于可能会遇到此帖子的任何人。解决方案如下:

select acct_no, month, sum(amount) as sumofamount, 
       substr(charge_type, 1, 3) as charge_type_substring,
       (
       case when (charge_type in ('CRE1', 'CRE2')
            then 'electronic payment'
            else 'cash'
       end) as payment_type
from   billing_data
where  charge_type in ('CRE1', 'CRE2', 'CASH')
group  by acct_no, month, substr(charge_type, 1, 3), 
       (
       case when (charge_type in ('CRE1', 'CRE2')
            then 'electronic payment'
            else 'cash'
       end)
       having sum(amount) != 0
order  by acct_no asc;

2 个答案:

答案 0 :(得分:0)

我相信你会这样:

select acct_no, month, sum(amount) as sumofamount, substr(charge_type, 1, 3) as charge_type_substring,
       case when (charge_type in ('CRE1', 'CRE2')
            then 'electronic payment'
            else 'cash'
       end as 'payment_type'
from   billing_data
where  charge_type in ('CRE1', 'CRE2', 'CASH')
group  by acct_no, month, charge_type_substring, payment_type
having sum(amount) != 0
order  by acct_no asc;

我对你的列别名采取了一些自由。这里最重要的一点是,sum()不属于您的组,因为我们正在使用公式聚合该列,但CASE语句的别名属于您的组,因为它没有被聚合一个公式。

答案 1 :(得分:0)

聚合函数不属于GROUP BY

您可以通过查看charge_type的前三个字母来解决您的问题:

select acct_no, month, sum(amount), substr(charge_type, 1, 3),
       (case when substr(charge_type, 1, 3) = 'CRE'
             then 'electronic payment'
             else 'cash'
        end) as payment_type
from  billing_data
where charge_type in ('CRE1', 'CRE2', 'CASH')
group by acct_no, month, substr(charge_type, 1, 3)
having sum(amount) <> 0
order by acct_no asc;