SQL:过滤掉过去一年没有购买过的客户

时间:2014-08-05 19:53:45

标签: sql sql-server

我有几张表格,上面有关于客户,他们的帐户信息和交易/销售的信息。许多客户可以使用某个帐户,但我想查找过去一年中没有购买任何东西的帐户数量。

Customer table = 
individual id
date added
first transaction date
gnc account number

Account table = 
account number
date added
expiration date
first transaction date
last purchase date

Transactions table = 
transaction id
sales date 
account number (null when customer doesn't have an account)

我需要将哪些内容合并到一个查询(子查询等)中,在那里我排除那些在过去一年内没有执行交易的帐户。

2 个答案:

答案 0 :(得分:0)

假设上次购买日期正确,您只需要一个简单的查询,如:

select a.*
from accounts a
where LastPurchaseDate >= dateadd(year, -1, getdate());

如果您想要号码,请使用select count(*)而不是select a.*

如果您想要未购买的号码,请使用<而不是>=

答案 1 :(得分:0)

PSEUDO CODE:

SELECT some columns 
FROM the account table
LEFT OUTER JOIN to INCLUDE ALL the accounts and only those that match from transaction
  on the account number 
 and the salesdate >= sysdate-365 (assuming this is a year)

除非限制在帐户表上,否则避免使用where子句..如果您在where子句中对事务表进行过滤,则将外连接更改为内连接,因为它将排除空值(除非您在每个位置使用OR)条款标准)

相关问题