我正在尝试在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一起使用的提示吗? 谢谢
答案 0 :(得分:0)
你似乎有几个问题:
distinct
inv_total或credit_total。如果两张发票总数相同,您只需要计算其中一张发票吗?sum
可以写成' SUM(inv_total - credit_total)'。这样更简单,不需要group by
子句。distinct
和group 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;