大佬教程收集整理的这篇文章主要介绍了如何有条件地统计每个企业的客户数量?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一张这样的桌子:
// 交易
ID | user_iD | business_ID | 金额 |
---|---|---|---|
1 | 10 | 1 | 3000 |
2 | 11 | 1 | 2500 |
3 | 10 | 2 | 4000 |
4 | 10 | 2 | 2000 |
5 | 11 | 3 | 3000 |
6 | 10 | 1 | 5000 |
7 | 10 | 3 | 3000 |
8 | 11 | 2 | 1000 |
我想计算每个企业从其他地方进行第一笔交易的客户数量。
注意 1:用户必须至少有一笔来自企业的交易才能被称为客户)。
注意 2: 将根据较小的 ID 检测到“第一笔交易”。
这是预期的结果:
+-------------+-------+ | business_ID | num | +-------------+-------+ | 1 | 0 | -- all its customers have had their first transaction this business | 2 | 2 | -- for users #10 and #11 (since these two users have had their first transaction somewhere elsE) | 3 | 2 | -- for user #10 and #11 +-------------+-------+
@H_419_119@知道我该怎么做吗?
我真的不知道如何开始编写这个查询。我所能做的就是计算每个企业的客户数量:
SELEct business_ID,count(1) num from (select user_id,business_ID from pos_transactions group by user_iD,business_ID) x
@H_419_119@解决方法
WITH cte1 AS ( select user_id,business_id,MIN(id) id FROM transactions GROUP BY user_id,business_id ),cte2 AS ( select user_id,MIN(id) id FROM transactions GROUP BY user_id ) SELECT cte1.business_id,@R_696_8164@te1.id > cte2.id) num FROM cte1 JOIN cte2 USING (user_id) GROUP BY business_id
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=fc9315adae0320bf673db9f0BACfdb90
,您可以使用
first_value()
和聚合:SELEct business_id,count(disTinct customer_id) as num_customers,count(disTinct case when firsT_Business_id <> business_id then customer_id end) as num_customers_from_elsewhere from (select t.*,first_value(business_id) over (partition by customer_id order by user_id) as firsT_Business_id from transactions t ) t group by business_id
以上是大佬教程为你收集整理的如何有条件地统计每个企业的客户数量?全部内容,希望文章能够帮你解决如何有条件地统计每个企业的客户数量?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。