获得具有多个产品的独特成员

问题描述 投票:1回答:2

我有一份可能有一种产品或多达10种产品的人员名单。我希望能够按产品类别对个人进行分类。例如:

Person| Product| Store_Online 
--------------------------------
A     | A_1    | Store
A     | A_2    | Online
B     | A_1    | Store
B     | A_1    | Store
C     | A_1    | Store
C     | A_1    | Online
C     | A_1    | Store
D     | A_1    | Online

我希望能够显示以下内容:

Person| Product| Store_Online
--------------------------------
A     |2Products| Both
B     | Single  | Store
C     | Single  | Both
D     |Single   |Online

我想不出能够给我什么,我希望得到的东西。

做一个独特的会给我一个人,但我不能肯定我可以用来获得理想的结果。

sql sql-server case-when
2个回答
1
投票

也许是简单的条件聚合

Select Person
      ,Product      = case when count(Distinct Product)      = 1 then 'Single' else concat(count(Distinct Product),'Products') end
      ,Store_Online = case when count(Distinct Store_Online) = 1 then max(Store_Online) else 'Both' end
  from @YourTable
 Group By Person

返回

Person  Product     Store_Online
A       2Products   Both
B       Single      Store
C       Single      Both
D       Single      Online

0
投票

我会用APPLY

SELECT DISTINCT t.person, 
       (CASE WHEN Product_CNT > 1 THEN '2Products' ELSE 'Single' END),
       (CASE WHEN Store_Online_CNT > 1 THEN 'Both' ELSE Store_Online END)
FROM table t CROSS APPLY
     ( SELECT COUNT(DISTINCT Product) AS Product_CNT, 
              COUNT(DISTINCT Store_Online) AS Store_Online_CNT
       FROM table t1
       WHERE t1.person = t.person
     ) t1;
© www.soinside.com 2019 - 2024. All rights reserved.