使用oracle

时间:2015-04-24 19:00:56

标签: node.js oracle

我正在使用Oracle运行查询:

SELECT
    c.customer_number,
    COUNT(DISTINCT o.ORDER_NUMBER),
    COUNT(DISTINCT q.QUOTE_NUMBER)
FROM
    Customer c
    JOIN Orders o on c.customer_number = o.party_number
    JOIN Quote q on c.customer_number = q.account_number
GROUP BY
    c.customer_number

这很好用,我可以得到顾客及他们的订单和报价。

然而,并非所有客户都有订单或报价,但我仍然想要他们的数据。当我使用LEFT JOIN时,我从Oracle收到此错误:

  

ORA-24347:聚合函数中的NULL列警告

似乎此错误是由于缺少订单和/或报价的客户最终COUNT(NULL)造成的。

如何在此查询中将COUNT个空值设置为0?

我可以执行COUNT(DISTINCT NVL(o.ORDER_NUMBER, 0))但如果订单/报价丢失则计数将显示到1,这是不好的。使用NVL(o.ORDER_NUMBER, NULL)会遇到同样的问题。

1 个答案:

答案 0 :(得分:1)

尝试使用内联视图:

SELECT
    c.customer_number,
    o.order_count,
    q.quote_count
FROM
    customer c,
    (   SELECT
            party_number,
            COUNT(DISTINCT order_number) AS order_count
        FROM
            orders
        GROUP BY
            party_number
    ) o,
    (   SELECT
            account_number,
            COUNT(DISTINCT quote_number) AS quote_count
        FROM
            quote
        GROUP BY
            account_number
    ) q
WHERE 1=1
    AND c.customer_number = o.party_number (+)
    AND c.customer_number = q.account_number (+)
;

很抱歉,我现在不使用任何数据库来测试它,或者测试ANSI SQL版本可能是什么。只是记忆。