按客户分组并连接在 SQL 中打开的产品

Grouping by Customer and concating products opened in SQL

我有一些数据想用来确定每个客户打开了哪些产品。有了这些数据,我想创建一个新列或多个列来指示这些产品。例如,请考虑以下数据。

CustomerKey ProductType
6458         Checking
6458         Savings
6458         Savings
6461         Savings
6461          IRA

对于客户 6458,我想要一个产品列来连接 his/her 产品,如下列方式之一。

Customer     Products               Checking/Savings         Savings/IRA
6458         Checking/Savings                1                     0
6461         Savings/IRA                     0                     1

除了 min/max 产品类型之外,我还能使用什么来连接所有成员?

Select Customerkey, producttype
from share
group by customerkey

产品组合的逻辑要求您将每个可能的组合硬编码为条件 sum,如下所示:

with p as (
    select distinct customerkey customer, Stuff(Products,1,1,'') Products
    from t
    cross apply (
        select distinct '/' + ProductType
        from t t2
        where t2.customerkey=t.customerkey
        for xml path('')
    )x(Products)
)
select *,
    max(case when products='Checking/Savings' then 1 else 0 end) as [Checking/Savings],
    max(case when products='IRA/Savings' then 1 else 0 end) as [IRA/Savings]
from p
group by customer, products

我会做这样的事情。这是使用 STRING_AGG 生成产品列表。然后对已知产品类型进行一些条件聚合,使该列 return 为 1 或 0。

create table #Something
(
    CustomerKey int
    , ProductType varchar(20)
)
insert #Something
select 6458, 'Checking' union all
select 6458, 'Savings' union all
select 6458, 'Savings' union all
select 6461, 'Savings' union all
select 6461, 'IRA'
;

--using a cte to ensure we get only distinct ProductTypes
with PreAggregate as
(
    select distinct CustomerKey
        , ProductType
    from #Something
)

select s.CustomerKey
    , Products = STRING_AGG(ProductType, '/') within group(order by ProductType)
    , Checking = max(case when ProductType = 'Checking' then 1 else 0 end)
    , Savings = max(case when ProductType = 'Savings' then 1 else 0 end)
    , IRA = max(case when ProductType = 'IRA' then 1 else 0 end)
from PreAggregate s
group by s.CustomerKey

drop table #Something