简体   繁体   English

SQL中如何查询这个结果? 或者也许在 python?

[英]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.

相关问题 如何在 python jupyter notebook 中运行 bigquery SQL 查询 - How to run a bigquery SQL query in python jupyter notebook 如何改进查询以在一行中生成数据? - How to improve the query to result the data in one row? 在 python 中使用 bigquery 结果的简单方法,其中查询仅返回一个结果 - Simple way to use bigquery result in python where the query return only one result 如何在 Flutter 中随机执行对 Firestore 的查询和排序结果 - how to perform query to Firestore and order result Randomly in Flutter 如何将具有不同值的虚拟列添加到 select 查询的结果中? - How to add a dummy column with different values to the result of a select query? 如何在 AWS 管理控制台中查看 DynamoDB 查询结果计数 - How to see DynamoDB Query result count in AWS management console 如何在另一个任务气流中使用查询(bigquery operator)的结果 - How to use the result of a query (bigquery operator) in another task-airflow Azure应用洞察中KQL查询结果如何添加超链接 - How to add hyperlink in KQL query result in Azure Application insight Python 中的 Google BigQuery 查询在使用 result() 时有效,但在使用 to_dataframe() 时出现权限问题 - Google BigQuery query in Python works when using result(), but Permission issue when using to_dataframe() 如何将查询结果直接写入谷歌云存储桶? - How to write query result to Google Cloud Storage bucket directly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM