简体   繁体   中英

How to can I use COUNT in a WHERE clause in Oracle

I'm working with the database HR and OE that is in oracle and I need to do a query that show: the name and last name of the customer, the number of the order and the list of products what have been bought for the customers that has more than 2 orders.

In the OE are all the tables that I'm using

Here is my query

SELECT cc.cust_first_name, cc.cust_last_name, oo.order_id, pi.product_name FROM
    customers cc INNER JOIN orders oo ON cc.customer_id = oo.customer_id INNER JOIN
    order_items oi ON oo.order_id = oi.order_id INNER JOIN product_information pi ON
    oi.product_id = pi.product_id
    GROUP BY cc.cust_first_name, cc.cust_last_name, oo.order_id, pi.product_name
    HAVING COUNT(oo.order_id) > 2;

And here is the database 在此处输入图片说明

use sub query because for group filter you have to use having that you used in your query but if you want where for that count number filter then you have use subquery or cte

    select * from
     (
     SELECT cc.cust_first_name, cc.cust_last_name, oo.order_id, 
    pi.product_name,COUNT(oo.order_id) as cnt
    FROM
    customers cc INNER JOIN orders oo ON cc.customer_id = oo.customer_id INNER JOIN
    order_items oi ON oo.order_id = oi.order_id INNER JOIN product_information pi ON
    oi.product_id = pi.product_id
    GROUP BY cc.cust_first_name, cc.cust_last_name, oo.order_id, pi.product_name
    ) a where a.cnt>2

You can use aggregation to bring the information together:

SELECT cc.cust_first_name, cc.cust_last_name,
       COUNT(DISTINCT oo.order_id) as num_orders,
       LISTAGG(pi.product_name) as products
FROM customers cc INNER JOIN
     orders oo
     ON cc.customer_id = oo.customer_id INNER JOIN
     order_items oi
     ON oo.order_id = oi.order_id INNER JOIN
     product_information pi
     ON oi.product_id = pi.product_id
GROUP BY cc.cust_first_name, cc.cust_last_name
HAVING COUNT(DISTINCT oo.order_id) > 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM