[英]How to write a SQL query to find out customers who have purchased at least two times every month of the year
[英]SQL: Filtering out customers who have not purchased over the past year
我有幾張桌子,上面有關於客戶,他們的帳戶信息以及交易/銷售的信息。 許多客戶可以使用一個帳戶,但是我想找到在過去一年中未購買任何商品的帳戶數量。
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)
我需要將哪些內容合並到查詢(子查詢等)中,在該查詢中,我排除了那些在過去一年中未執行交易的帳戶。
假設最后一次購買日期是正確的,則只需要一個簡單的查詢,例如:
select a.*
from accounts a
where LastPurchaseDate >= dateadd(year, -1, getdate());
如果需要數字,請使用select count(*)
而不是select a.*
。
如果您想要尚未購買的電話號碼,請使用<
而不是>=
。
偽代碼:
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子句中對事務處理表進行過濾,則它將外部聯接更改為內部聯接,因為它將排除空值(除非您對每個where子句條件進行OR運算)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.