PL / SQL SUM差异示例

时间:2014-09-16 21:17:17

标签: sql oracle plsql

我正在尝试在PL / SQL中实现这个SQL代码

SQL代码:

select  SUM(SUM(distinct inv_total) - SUM(distinct credit_total) ) as TOTAL from invoice
where cus_id =95 
group by inv_total, credit_total

PL / SQL代码:

Declare 

total invoice.inv_total%TYPE;
cust_id NUMBER := 95;
BEGIN

select  SUM(SUM(distinct inv_total) - SUM(distinct credit_total) ) 
INTO total from invoice
where cus_id= cust_id;
dbms_output.put_line('Total is ' || total);

END;

ERROR at line 1: 
ORA-00978: nested group function without GROUP BY 
ORA-06512: at line 8 

有关如何将GROUP BY与PL / SQL一起使用的提示吗? 谢谢

4 个答案:

答案 0 :(得分:0)

你似乎有几个问题:

  1. 我发现你实际上不太可能想要distinct inv_total或credit_total。如果两张发票总数相同,您只需要计算其中一张发票吗?
  2. 如果没有明确的,sum可以写成' SUM(inv_total - credit_total)'。这样更简单,不需要group by子句。
  3. 原始查询按inv_total和credit_total分组。这似乎也不对,因为您不太可能希望根据这样的总数对多行进行分组。
  4. 如果您真的想要distinctgroup by,那么您必须在PL / SQL块中包含group by,就像在原始版本中一样SQL语句。

答案 1 :(得分:0)

试试这个: -

DECLARE
total invoice.inv_total%TYPE;
cust_id NUMBER := 95;
BEGIN
select  SUM( inv_total - credit_total) 
INTO total from invoice
where cus_id= cust_id;
dbms_output.put_line('Total is ' || total);
END;
/

答案 2 :(得分:0)

您可以将代码编写为;

Declare 

total invoice.inv_total%TYPE;
cust_id NUMBER := 95;
BEGIN

select  SUM(
             (select distinct i1.inv_total
                from invoice i1
               where i1.cus_id = I.cus_id ) 
            )  
        - 
        SUM(
             (select distinct i2.credit_total 
                from invoice i2
               where i2.cus_id = I.cus_id ) 
            ) 
INTO total 
from invoice i
where i.cus_id= cust_id;
dbms_output.put_line('Total is ' || total);

END;

您还可以将代码编写为

Declare 

total invoice.inv_total%TYPE;
cust_id NUMBER := 95;
BEGIN

select  SUM(inv_total - credit_total)
INTO total 
from         (select distinct i1.inv_total, i1.credit_total
                from invoice i1
               where i.cus_id = cust_id ) 
             ); 
dbms_output.put_line('Total is ' || total);

END;

选择适合您要求的

答案 3 :(得分:-1)

如果是我

选择cus_id,SUM(SUM(inv_total) - SUM(credit_total)) INTO cus_id,总计 从发票 其中cus_id = cust_id group by cus_id;