簡體   English   中英

SQL查詢:查找在一年中購買了多本書的客戶

[英]SQL Query: find customers who purchased more than one book in a given year

這是數據庫模式:

Books (bookid, title, author, year)
Customers (customerid, name, email)
Purchases (customerid, bookid, year)
Reviews (customerid, bookid, rating)
Pricing (bookid, format, price)

我如何找到在2003年購買超過一本書的客戶(顯示其姓名和電子郵件地址)?

SELECT name, email, COUNT(p.customerId) as purchases_in_2003
FROM Customers c
INNER JOIN Purchases p ON c.customerId = p.customerId
WHERE p.year = 2003
GROUP BY name, email
HAVING purchases_in_2003 > 1

幾乎就像您的英語問題所表達的...只是翻譯成SQL ...

Select * From Customers C
Where (Select Count(*) From Purchases
       Where customerid = C.customerid
           And Year = 2003) > 1

另一種選擇:

select
  cu.name
 ,cu.email
 ,count(*) as books_purchased
from
  customers cu
 ,purchases pu
where cu.customerid = pu.customerid
  and pu.year = 2003
group by
  cu.name
 ,cu.email
having
  count(*) > 1

暫無
暫無

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

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