尝试将select sum和count statemenents合并为一个(oracle db)

时间:2015-09-25 22:08:49

标签: sql oracle select join

我需要写一个声明来获取客户总数和所有帐户总和的总和。我能够单独完成每一个,但我不能让它们成为一个声明。错误消息的含义是什么,FROM应该去哪里?

这是贷款总额的声明

SQL> SELECT SUM(amount) as "total"
     FROM loan, borrower
     WHERE borrower.loan_number = loan.loan_number;

这是客户数量的声明

   SQL> SELECT COUNT(*)
        FROM customer;

我已经将它们组合在一起但是我收到了一条错误信息,你可以看到。

> SQL> SELECT
2  (SELECT COUNT(*) as "Total Customers" from customer)
3  (SELECT SUM(amount) as "Total Loan Values"
4  FROM borrower, loan 
5  WHERE borrower.loan_number = loan.number);
(select sum(amount) as "Total Loan Values"
 *
 ERROR at line 3:
 ORA-00923: FROM keyword not found where expected

3 个答案:

答案 0 :(得分:1)

由于您customer的查询只返回一行,您可以cross join使用其他问题:

SELECT     SUM(amount) as total, cnt
FROM       loan
JOIN       borrower ON borrower.loan_number = loan.loan_number;
CROSS JOIN (SELECT COUNT(*) AS cnt 
            FROM   customer) 

答案 1 :(得分:1)

试试这个:

SELECT
  (SELECT COUNT(*) as "Total Customers" from customer),
  (SELECT SUM(amount) as "Total Loan Values"
  FROM borrower, loan 
  WHERE borrower.loan_number = loan.number)
FROM DUAL;
你错过了一个逗号;另外,你总是需要一个FROM子句。如果没有要命名的表,则DUAL用作虚拟。

答案 2 :(得分:0)

您可以修改您的查询,如下所示

SELECT
(SELECT COUNT(*) as "Total Customers" from customer),
(SELECT SUM(amount) as "Total Loan Values"
FROM borrower, loan 
WHERE borrower.loan_number = loan.number)
FROM DUAL;