【问题标题】:Group by substr in Oracle在 Oracle 中按 substr 分组
【发布时间】: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


【解决方案1】:

我相信你会这样做:

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() 不属于您的组 by,因为我们正在使用公式聚合该列,但是您的 CASE 语句的别名确实属于您的组 by,因为它不是由公式聚合的.

【讨论】:

  • 谢谢!这有帮助!但是我知道你不能在 group-by 子句中使用别名。
  • 我想我明白了。我在括号中添加了整个 case 语句减去 group by 的别名,它起作用了!我将使用最终结果编辑原始帖子。再次感谢!
【解决方案2】:

聚合函数不属于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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多