我想创建一个SQL查询,列出所有已经放置了高于平均订单数的客户

时间:2016-12-04 05:44:11

标签: sql oracle join

SQL查询以列出已经放置了高于平均订单数量的所有客户。

订单详细信息显示在NW_orders表中,客户信息显示在NW_Customers表中。

首先,我计算了所有客户的平均订单数量。然后我想只拉出订单大于平均订单数量的客户。

我的查询:

SELECT 
    C.customerid, C.companyname, COUNT(O.orderid) AS cnt
FROM 
    NW_customers C
LEFT JOIN 
    NW_orders O ON O.customerID = C.Customerid 
GROUP BY 
    C.customerid 
HAVING 
   cnt > (SELECT COUNT(O.OrderID) / COUNT(DISTINCT(c.customerid)) AS Avg
          FROM NW_orders O
          LEFT JOIN NW_customers C ON O.customerID = C.Customerid)

我收到错误

  

ORA-00904:“CNT”:标识符无效

有人可以帮忙纠正错误吗?

2 个答案:

答案 0 :(得分:2)

使用公用表表达式:

WITH cte AS (
    SELECT o.customerid, COUNT(o.orderid) AS cnt
    FROM NW_orders o
    GROUP BY o.customerid
)

SELECT t.customerid
FROM cte t
WHERE t.cnt > (SELECT AVG(cnt) FROM cte)

如果您想引入实际的客户信息,可以在上述查询中添加联接:

SELECT t1.*, t2.*
FROM cte t1
INNER JOIN NW_customers t2
    ON t1.customerid = t2.customerid
WHERE t1.cnt > (SELECT AVG(cnt) FROM cte)

答案 1 :(得分:2)

这是分析函数的经典之作。

cutomerId

select      customerID

from       (select      customerID
                       ,count(*)                as customer_orders
                       ,avg  (count(*)) over () as avg_customer_orders

            from        NW_orders

            group by    customerID
            )

where       customer_orders > avg_customer_orders
;

完整的客户信息

select      *

from        NW_customers

where       customerID in
            (
                select      customerID

                from       (select      customerID
                                       ,count(*)                as customer_orders
                                       ,avg  (count(*)) over () as avg_customer_orders

                            from        NW_orders

                            group by    customerID
                            )

                where       customer_orders > avg_customer_orders
            )
;

完整的客户信息+订单信息

select      o.customer_orders
           ,o.avg_customer_orders
           ,c.*

from                    NW_customers    c

            join        (select     customerID
                                   ,count(*)                as customer_orders
                                   ,avg  (count(*)) over () as avg_customer_orders

                        from        NW_orders

                        group by    customerID
                        ) o

            on          o.customerID    =
                        c.customerID


where       o.customer_orders > o.avg_customer_orders
;