[英]How to query this result in SQL? or maybe in python?
I have a table with multiple user_id and each one can redeem a discount code like this:我有一个包含多个 user_id 的表,每个 user_id 都可以兑换这样的折扣代码:
user_id用户身份 | discount_code优惠码 |
---|---|
1 1个 | A一种 |
2 2个 | B乙 |
3 3个 | A一种 |
1 1个 | B乙 |
2 2个 | A一种 |
1 1个 | A一种 |
1 1个 | B乙 |
2 2个 | A一种 |
2 2个 | B乙 |
3 3个 | A一种 |
I have to count the overlap of users for each discount code.我必须计算每个折扣代码的用户重叠情况。
I think this should be the result:我想应该是这样的结果:
A一种 | B乙 | |
---|---|---|
A一种 | 3 3个 | 2 2个 |
B乙 | 2 2个 | 2 2个 |
Consider below approach考虑以下方法
select * from (
select t1.discount_code, t2.discount_code code, count(distinct t1.user_id) value
from your_table t1
join your_table t2
using(user_id)
group by 1, 2
)
pivot (any_value(value) for code in ('A', 'B'))
if applied to sample data in your question - output is如果应用于您问题中的示例数据 - output 是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.