簡體   English   中英

使用SQL查詢查找訂購> x類產品的客戶的詳細信息

[英]Using SQL query to find details of customers who ordered > x types of products

請注意,我在這里看到過類似的查詢,但認為我的查詢不同,值得單獨提問。

假設有一個包含以下表的數據庫:

  1. customer_table with customer_ID(key field),customer_name
  2. order_table with order_ID(key field),customer_ID,product_ID

現在假設我想找到訂購了10種以上不同類型產品的所有客戶的名稱,以及他們訂購的產品類型的數量。 同一產品的多個訂單不計算在內。

我認為下面的查詢應該有效,但有以下問題:

  1. 使用count(distinct xxx)通常是否允許使用“group by”語句?
  2. 我使用標准方法的方法是什么? 有沒有人有更好的想法(例如沒有涉及臨時表)?

以下是我的查詢

select T1.customer_name, T1.customer_ID, T2.number_of_products_ordered
from customer_table T1
inner join 
(
    select cust.customer_ID as customer_identity, count(distinct ord.product_ID) as number_of_products_ordered
    from customer_table cust
    inner join order_table ord on cust.customer_ID=ord.customer_ID
    group by ord.customer_ID, ord.product_ID
    having count(distinct ord.product_ID) > 10
) T2
on T1.customer_ID=T2.customer_identity
order by T2.number_of_products_ordered, T1.customer_name

這不是你想要的嗎? 似乎有點簡單。 在SQL Server上測試它 - 工作正常。

SELECT customer_name, COUNT(DISTINCT product_ID) as products_count FROM customer_table
INNER JOIN orders_table ON customer_table.customer_ID = orders_table.customer_ID
GROUP BY customer_table.customer_ID, customer_name
HAVING COUNT(DISTINCT product_ID) > 10

你可以更簡單地做到:

select

    c.id,
    c.cname,
    count(distinct o.pid) as `uniques`

from o join c
on c.id = o.cid

group by c.id

having `uniques` > 10

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM