首页 > 解决方案 > Sql - 查询以计算编号。每月的买家

问题描述

我真的需要你的帮助来创建一个查询,我可以在其中显示 2017 年 1 月至 2017 年 12 月期间一个月内下单超过 1 个订单的买家数量。

此外,没有。这些买家中没有在接下来的 12 个月内再次订购。

以下是我的数据示例。

日期 CID(客户 ID) 订单号
2017-02-03 0:23 924832 000023149
2017-02-05 0:11 924162 000092384
2017-07-01 0:53 914861 000023182
2017-08-09 0:42 924832 000021219

输出应该是这样的

> 1个订单的买家 未订购下一个 12M 的买家
2017-01-01 122 92
2017-02-01 74 24
2017-03-01 216 107

标签: sqlsql-server

解决方案


这应该与您的描述相匹配:

with cte as
 (
   select
      ca.ym
     ,cid
     -- flag buyers who made more than 1 order in a month
     ,case when count(*) > 1 then 1 else 0 end as multi_buy

     -- flag buyers that didn't order again within the next 12 months
     ,case when LEAD(ym,1,ym) -- month of next order
                over (partition by CID
                      order by ym) < DATEADD(month, 13, ym)
           then 0 
           else 1
      end as no_buy_within_range
   from orders
   CROSS APPLY 
    ( -- truncate the OrderDate to the 1st of month
      SELECT convert(Date, DATEADD(month, DATEDIFF(month, 0, OrderDate), 0)) as ym
    ) as ca
   group by
      ym
     ,cid
 )
select 
   ym
  ,sum(multi_buy)
  ,sum(no_buy_within_range)
from cte
group by ym
order by ym

推荐阅读