此处不允许使用序列号

63lcw9qa  于 2022-10-04  发布在  Oracle
关注(0)|答案(2)|浏览(201)

我需要同时使用序列的GROUP BY和NEXTVAL。我怎么能做到这一点呢?我不确定如何修改查询以使其工作

SELECT BCS_RPT_AGGREGATOR_COSTCENTER_seq.nextval AS ID,
    TO_DATE(TO_CHAR(brt.TRANSACTION_DATE, 'YYYY-MM-DD'), 'YYYY-MM-DD'),
           brt.COST_CENTER,
           COUNT(brt.COST_CENTER),
           SUM(brt.COLLECTION_AMOUNT),
           SUM(brt.COMMISSION_AMOUNT),
           SUM(brt.SERVICE_FEE),
           SUM(brt.BANK_INCOME_AMOUNT)
    FROM  BCS_RPT_TRANSACTION brt
    WHERE brt.IS_AGGREGATED_C =0
    AND brt.COST_CENTER = :costCenter   GROUP BY brt.COST_CENTER,
             TO_DATE(TO_CHAR(brt.TRANSACTION_DATE, 'YYYY-MM-DD'), 'YYYY-MM-DD');
vjhs03f7

vjhs03f71#

不能在GROUP BY查询中使用SEQUENCE。您可以使用子查询按如下方式编辑查询:

SELECT
    bcs_rpt_aggregator_costcenter_seq.NEXTVAL AS id,
    a.*
FROM
    (
        SELECT
            to_date(to_char(brt.transaction_date, 'YYYY-MM-DD'), 'YYYY-MM-DD'),
            brt.cost_center,
            COUNT(brt.cost_center),
            SUM(brt.collection_amount),
            SUM(brt.commission_amount),
            SUM(brt.service_fee),
            SUM(brt.bank_income_amount)
        FROM
            bcs_rpt_transaction brt
        WHERE
                brt.is_aggregated_c = 0
            AND brt.cost_center = :costcenter
        GROUP BY
            brt.cost_center,
            to_date(to_char(brt.transaction_date, 'YYYY-MM-DD'), 'YYYY-MM-DD')
    ) a;
3yhwsihp

3yhwsihp2#

简而言之,这是您所拥有的:

SQL> create sequence seq;

Sequence created.

SQL> select seq.nextval,
  2         deptno,
  3         sum(sal) sum_sal
  4  from emp
  5  group by deptno;
select seq.nextval,
           *
ERROR at line 1:
ORA-02287: sequence number not allowed here

一种选择是使用Current Query(不带序列)作为子查询(或CTE,就像我在下面的示例中所做的那样),然后在主select中使用您收集的数据并添加序列号:

SQL> with temp as
  2    (select deptno,
  3            sum(sal) sum_sal
  4     from emp
  5     group by deptno
  6    )
  7  select seq.nextval,
  8         deptno,
  9         sum_sal
 10  from temp;

   NEXTVAL     DEPTNO    SUM_SAL
---------- ---------- ----------
         1         30       9400
         2         20      10875
         3         10       8750

SQL>

然后,您的代码将如下所示:

WITH
   temp
   AS
      (  SELECT TO_DATE (TO_CHAR (brt.transaction_date, 'YYYY-MM-DD'),
                         'YYYY-MM-DD'),
                brt.cost_center,
                COUNT (brt.cost_center),
                SUM (brt.collection_amount),
                SUM (brt.commission_amount),
                SUM (brt.service_fee),
                SUM (brt.bank_income_amount)
           FROM bcs_rpt_transaction brt
          WHERE     brt.is_aggregated_c = 0
                AND brt.cost_center = :costcenter
       GROUP BY brt.cost_center,
                TO_DATE (TO_CHAR (brt.transaction_date, 'YYYY-MM-DD'),
                         'YYYY-MM-DD'))
SELECT bcs_rpt_aggregator_costcenter_seq.NEXTVAL AS id, 
       t.*
  FROM temp t;

相关问题