【发布时间】:2018-02-20 21:16:37
【问题描述】:
下面是一个示例查询:
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;
【问题讨论】:
-
问题是您正在尝试按聚合进行分组:
sum(amount)。您要汇总金额还是按金额分组?此外,您没有按payment_type字段分组,也没有按公式聚合。它应该放在您的 GROUP BY 中。 -
感谢您的反馈。我正在尝试将两种费用类型 CRE1 和 CRE2 的金额相加并在一行中显示金额
-
另外,您需要在 group by 子句中包含
case when (charge_type in ('CRE1', 'CRE2') then 'electronic payment' else 'cash'。 (或按charge_type分组,但我认为这不是你想要的。
标签: sql oracle group-by substr regexp-substr