首页 > 解决方案 > 创建一个数据集,该数据集在任何记录存在时都生成 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 年之前)上。

标签: sqlsql-servertsqlgroup-bypivot

解决方案


您似乎正在寻找条件聚合。您想要的逻辑如下所示:

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

推荐阅读