我列出了可能拥有一种产品或最多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
我想不出能给我我希望得到的东西。
与众不同会给我一个人,但我对我可以用来为我带来理想结果的态度并不肯定。
答案 0 :(得分: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
答案 1 :(得分: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;