oracle 如何使用带有Partition by子句的case语句并避免Group by

3xiyfsfu  于 2023-08-03  发布在  Oracle
关注(0)|答案(1)|浏览(105)

在使用case和partition by时,我需要避免使用group by子句。这可行吗?我保持sum(case...)以避免group by,它抛出不允许的窗口函数。

select DISTINCT
        a.CIF
       ,a.accnt
     --,a.prod --how to avoid
        ,case when prod='dbal' then SUM(BAL) OVER (PARTITION BY a.ACCNT) end as ACCNT_bal
        ,case when prod='cbal' then SUM(BAL) OVER (PARTITION BY a.ACCNT) end as CREDIT_bal
    ---  ,SUM(case when prod='dbal' then SUM(BAL) OVER (PARTITION BY a.ACCNT) end) as ACCNT_bal
     ---   ,SUM(case when prod='cbal' then SUM(BAL) OVER (PARTITION BY a.ACCNT) end) as CREDIT_bal
        from q2.accnt a 
        join balance d on a.id=d.id
        where date=20230709
        AND prod in( 'dbal', 'cbal') 
        group by a.CIF, a.accnt --,a.pord

字符串
我得到以下错误时,上述是使用。
ORA-30483:此处不允许使用窗口函数30483。00000 -“此处不允许使用窗口函数”

  • 原因:窗口函数只允许在查询的SELECT列表中使用。
    窗口函数不能作为另一个窗口或组函数的参数。
  • 行动:
    行错误:3柱:38
2izufjch

2izufjch1#

删除OVER逻辑并使用普通聚合,将case逻辑放在SUM()中:

select a.CIF
       ,a.accnt
       ,SUM(case when prod='dbal' then BAL end) as ACCNT_bal
       ,SUM(case when prod='cbal' then BAL end) as CREDIT_bal
  from q2.accnt a 
  join balance d on a.id=d.id
  where date=20230709
   AND prod in( 'dbal', 'cbal') 
  group by a.CIF, a.accnt

字符串
如果你真的想聚合这些余额 * 跨 * CIF值(确保这是你真正想要的,它会为相同的acct的每一行显示相同的余额),你可以将SUM Package 在另一个窗口化的SUM中。

select a.CIF
     ,a.accnt
     ,SUM(SUM(case when prod='dbal' then BAL end) OVER (PARTITION BY accnt) as ACCNT_bal
     ,SUM(SUM(case when prod='cbal' then BAL end) OVER (PARTITION BY accnt) as CREDIT_bal
from q2.accnt a 
join balance d on a.id=d.id
where date=20230709
 AND prod in( 'dbal', 'cbal') 
group by a.CIF, a.accnt

相关问题