sql - 创建一个数据集,该数据集在任何记录存在时都生成 0/1 标志
问题描述
我有一张表,设计为每个成员每月每个产品使用情况有 1 行。共有三种产品。大多数人只使用一种产品,但有些人使用其他产品的组合。理想情况下,我希望有一个如下所示的结果集:
但是我只能让它显示和现在一样,但是有 1 和 0。因此,如果一个人使用了所有三种产品,则将有 3 行 1,而不是 1 行 3 1。
这是代码现在的样子:
WITH
dist_visit_typ_cte(visit_month, person_id, product_type) as
(select distinct visit_month, person_id, product_type
from product_transaction_table),
visit_count_cte (visit_month, person_id, prod_a_usage, prod_b_usage, prod_c_usage) as
(select distinct visit_month
,CASE WHEN product_type = 'A' then 1, else 0 end as prod_a_usage
,CASE WHEN product_type = 'B' then 1, else 0 end as prod_b_usage
,CASE WHEN product_type = 'C' then 1, else 0 end as prod_c_usage
from dist_visit_typ_cte
group by
visit_month
,CASE WHEN product_type = 'A' then 1, else 0
,CASE WHEN product_type = 'B' then 1, else 0
,CASE WHEN product_type = 'C' then 1, else 0
它位于旧版本的 SQL-Server(2016 年之前)上。
解决方案
您似乎正在寻找条件聚合。您想要的逻辑如下所示:
select visit_month, person_id,
max(case when product_type = 'A' then 1 else 0 end) prod_a_usage,
max(case when product_type = 'B' then 1 else 0 end) prod_b_usage,
max(case when product_type = 'C' then 1 else 0 end) prod_c_usage
from dist_visit_typ_cte
group by visit_month, person_id
推荐阅读
- ios - iPhone XR 中的 WKWebView 重叠状态栏
- ios - 在 Swift 中,我如何知道单词是否包含在 UILabel 中
- python-3.x - Python 3 Pandas,将数据附加到现有的 Excel 工作表
- python - Web-scraping:访问大列表中的文本信息
- vue.js - 父更新时VUE Js子不更新
- visual-studio - 在 Visual Studio 2020 中构建时,在第一次构建错误时停止而不安装任何扩展
- linux - 将 PDF 与文件名中的空格结合起来
- python - 如何获得数字 = [“12”、“145”、“45”、“12.4”、“45,14”、“15 645”] 数字
- windows-subsystem-for-linux - 如何从另一个访问 WSL 实例?
- javascript - 如何合并两个文件夹树