sql - 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 |
解决方案
这应该与您的描述相匹配:
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
推荐阅读
- python - 如何使用 store = True 更新具有计算字段的旧记录
- sql - 总结 T-SQL 中的连续值
- data-distribution-service - DDS协议可以用于连接到不同网络的设备之间进行通信吗?如何?
- ssl - 如何在 PostgreSQL 9.4 中配置 SSL 证书?
- ios - PickerView 已禁用且在 SwiftUI 中不起作用
- adsense - Google AdSense ERR_ADDRESS_INVALID
- discord - 如何让机器人向每个服务器成员发送消息
- opencv - 在 OpenCV 中将深度图像从毫米转换为米
- kubernetes - Kubernetes 中的入口 nginx 路由(使用 nginx 反向代理从 docker-compose 转换)
- java - 401- 从 Spring Boot 应用程序使用 REST API Dynamics CRM 和 Azure AD 进行未经授权的身份验证