我有一张看起来像这样的表:
CustomerID ItemType
001 'a'
001 'b'
001 'c'
001 'd'
002 'd'
如何构造类似于以下内容的select语句:
CASE WHEN ItemType = 'a' THEN 1 ELSE 0 END as Aexists,
CASE WHEN ItemType = 'b' THEN 1 ELSE 0 END as Bexists,
CASE WHEN ItemType = 'c' THEN 1 ELSE 0 END as Cexists,
CASE WHEN ItemType = 'd' THEN 1 ELSE 0 END as Dexists,
CASE WHEN ItemType = 'e' THEN 1 ELSE 0 END as Eexists,
GROUP BY CustomerID
结果如下所示:
CustomerID, Aexists, Bexists, Cexists, Dexists, Eexists
001 1 1 1 1 0
002 0 0 0 1 0
我很困惑如何判断这些物品是否存在,因为它们分布在各行上;我只希望每个客户返回一行。
答案 0 :(得分:1)
足够近。使用汇总函数MAX
select
CustomerID,
max(CASE WHEN ItemType = 'a' THEN 1 ELSE 0 END) as Aexists,
max(CASE WHEN ItemType = 'b' THEN 1 ELSE 0 END) as Bexists,
max(CASE WHEN ItemType = 'c' THEN 1 ELSE 0 END) as Cexists,
max(CASE WHEN ItemType = 'd' THEN 1 ELSE 0 END) as Dexists,
max(CASE WHEN ItemType = 'e' THEN 1 ELSE 0 END) as Eexists
from t
GROUP BY CustomerID