簡體   English   中英

SQL查找每月至少訂購一次的客戶

[英]SQL to find customers that have ordered at least once a month

我需要查詢在指定年份或多年內每月至少訂購一次的客戶。 我不想划分他們有多少訂單,平均每年至少看到12筆訂單。 我需要知道,他們實際上在該范圍內每月至少訂購一次。

到目前為止,我的工作在下面,但是似乎應該有更好的方法來做到這一點。 有沒有更好的方法來編寫此查詢?

with CustomersThatOrderAtLeastOnceAMonth as (
    select c.username, c.id
    from customer c
    where exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-01-01' and '2015-02-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-02-01' and '2015-03-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-03-01' and '2015-04-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-04-01' and '2015-05-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-05-01' and '2015-06-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-06-01' and '2015-07-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-07-01' and '2015-08-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-08-01' and '2015-09-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-09-01' and '2015-10-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-10-01' and '2015-11-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-11-01' and '2015-12-01')   
      and exists (select 1 from orders o where c.id = o.CustomerId and o.orderdate between '2015-12-01' and '2016-01-01')   
)

怎么樣:

select customerid
from orders o
where o.orderdate >= '2015-01-01' and o.orderdate < '2016-01-01' 
group by customerid
having count(distinct year(orderdate)*100 + month(orderdate)) = 12;

如果您有orders(customerid, orderdate)的索引orders(customerid, orderdate) ,我不確定這是否更快。 它可能取決於數據的分布。 顯然,如果您有1,000,000個客戶,並且在整個月中只有1個訂單,那是1月的唯一訂單,那么您的代碼可能會更快。

暫無
暫無

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

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