SQL查询在给定月份内的所有购买

时间:2016-03-01 17:08:44

标签: sql

我正在阅读SQL教程,并遇到了这个问题。 我已经被困了一段时间。

客户

id INTEGER PRIMARY KEY    
lastname VARCHAR    
firstname VARCHAR

购买

id INTEGER PRIMARY KEY    
customers_id INTEGER FOREIGN KEY customers(id)    
purchasedate DATETIME    
purchaseamount REAL

Write a statement that gives a list of all customers who purchases something this month.

我知道我想在customer_id上加入表格,然后获取月份为2月的客户名称,这看起来是否合适?

SELECT * from Purchases
    inner join Customers
    on Purchases.customers_id=Customers.id
WHERE MONTH(purchasedate) = 2

3 个答案:

答案 0 :(得分:3)

是的,或者为了避免你可以编写的整个distinct业务

SELECT id, LastName, firstname FROM Customers
WHERE EXISTS ( SELECT 1 FROM Purchases 
               WHERE customers_id=Customers.id
               AND MONTH(purchasedate)=2 AND YEAR(purchasedate)=2016 )

答案 1 :(得分:2)

我将使用EXISTS,这将避免重复

SELECT Customers.id,
       Customers.LastName,
       Customers.firstname
FROM   Customers
WHERE  EXISTS (SELECT 1
               FROM   Purchases
               WHERE  Purchases.customers_id = Customers.id
                      AND Month(purchasedate) = 2) 

考虑您想要提取在任何一年2月购买的客户信息

答案 2 :(得分:1)

您的查询将返回一个包含重复名称的列表。只需添加DISTINCT

即可

请勿使用*,只需添加您需要的字段。

还包括id,以防两个ppl具有相同的名字和姓氏

SELECT DISTINCT Customers.id, Customers.LastName, Customers.firstname 
from Purchases
inner join Customers
  on Purchases.customers_id = Customers.id
WHERE MONTH(purchasedate) = 2

如果您只想要当月销售额。你需要指定你的RDBMS,因为日期函数是不同的。

例如在postgres sql中你可以使用 Get first date of month in postgres

SELECT DISTINCT Customers.id, Customers.LastName, Customers.firstname 
from Purchases
inner join Customers
  on Purchases.customers_id = Customers.id
WHERE date_trunc('month', current_date) = date_trunc('month', purchasedate)