我有下表,它检查客户有多少订单将用作我的PowerPivot模型的查找表/过滤器
| CustomerID | OrderCntOne | OrderCntTwo | OrderCntThree |
---------------------------------------------------------------
| 0 | X | | |
| 0 | | X | |
| 0 | | | X |
| 1 | X | | |
| 2 | X | | |
| 3 | X | | |
| 3 | | X | |
| 4 | X | | |
| 4 | | X | |
| 4 | | | X |
---------------------------------------------------------------
是使用此SQL查询创建的,查看客户给定订单的编号(订单计数),并根据客户在其生命周期中是否有1,2或3个订单忽略任何内容来设置x超过3个订单。
SELECT [CustomerID],
CASE
WHEN OrderCount = 1 THEN 'X'
END AS OrdCntOne,
Case
WHEN OrderCount = 2 THEN 'X'
End as OrdCntTwo,
Case
WHEN OrderCount = 3 THEN 'X'
End as OrdCntThree,
FROM [dbo].[Table]
group by CustomerID, ordercount
但是,我希望该表看起来像这样,因此每个客户ID只有一行
| CustomerID | OrderCntOne | OrderCntTwo | OrderCntThree |
---------------------------------------------------------------
| 0 | X | X | X |
| 1 | X | | |
| 2 | X | | |
| 3 | X | X | |
| 4 | X | X | X |
---------------------------------------------------------------
但我不确定如何只使用正确的" x'#34;每行显示1个客户ID在该单个ID旁边。由于订单数量导致多个客户ID,因此无法按客户ID进行分组。
任何想法都会有所帮助。
答案 0 :(得分:3)
只需从ordercount
移除group by
,然后使用MAX
覆盖case
个表达式。
select [CustomerID],
max(case when OrderCount = 1 then 'X' end) as OrdCntOne,
max(case when OrderCount = 2 then 'X' end) as OrdCntTwo,
max(case when OrderCount = 3 then 'X' end) as OrdCntThree
from [dbo].[Table]
group by CustomerID;