获得具有多种产品的不同成员
getting distinct member with multiple products
我有一份可能拥有一种产品或最多 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
我想不出什么东西可以给我我希望得到的东西。
做一个与众不同的人会让我成为一个人,但我不确定我可以用什么来获得理想的结果。
我会使用 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;
也许是一个简单的条件聚合
例子
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
Returns
Person Product Store_Online
A 2Products Both
B Single Store
C Single Both
D Single Online
我有一份可能拥有一种产品或最多 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
我想不出什么东西可以给我我希望得到的东西。
做一个与众不同的人会让我成为一个人,但我不确定我可以用什么来获得理想的结果。
我会使用 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;
也许是一个简单的条件聚合
例子
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
Returns
Person Product Store_Online
A 2Products Both
B Single Store
C Single Both
D Single Online