下面是我试图实现的一个简单示例:
本质上,我想采用这样的数据集:
原始数据
进入:
输出
我想用某种CASE语句来检查任何一种水果是否有多种颜色,然后是"多个"ELSE";"颜色";,但不确定如何构建该逻辑来检查单个项目的多个不同值。提前感谢您的帮助!
declare @table table
( fruit varchar(250),
color varchar(250)
)
insert into @table (fruit, color)
values
('banana', 'yellow')
, ('banana', 'yellow')
, ('apple', 'red')
, ('apple', 'green')
select distinct t.fruit, case when d.color = 1 then t.color else 'multiple' end as color from @table t
left join
(
select fruit, count(distinct color) as color from @table
group by fruit
) d on d.fruit = t.fruit
这个有效。使用count distinct来获取颜色的数量,然后在外部选择一个distinct。
select fruit
,case when count(distinct Color) > 1 then 'Multiple' else max(color) end as Color
from t
group by fruit
水果 | |
---|---|
Apple | 多个 |
香蕉 | 黄色 |
Cherry | 多个 |
橙色 | 橙色 |