我需要像这样的选择语句
select Invoice, Original Color,Product,Option Color, Result_column from table
其中Result_column值基于以下条件
如果发票中的所有Option_Colors均为蓝色,则结果列为 蓝色
如果发票中的所有Option_Colors均为红色,则结果列为 红色
如果发票的Option_Colors中的颜色混合,则 任何颜色Original_Color列显示。
答案 0 :(得分:0)
您可以使用case语句,这也将更加容易。
select Invoice, Original_Color,Product,Option_Color, case when Option_Color not in
('RED', 'GREEN', 'BLUE') THEN Original_Color else Option_Color end Result_column from
table
答案 1 :(得分:0)
您可以尝试:
with mytablecnt(Invoice, Cnt) as
(
select Invoice, count(distinct OptionColor) as Cnt
from mytable
group by Invoice
)
select t1.Invoice, t1.OriginalColor, t1.OptionColor,
case
when t2.Cnt = 1 then OptionColor
when t2.Cnt != 1 then OriginalColor
end as ResultColumn
from mytable t1
left join mytablecnt t2
on t1.Invoice = t2.Invoice
order by Invoice
答案 2 :(得分:0)
尝试一下。
select Invoice, OriginalColor, OptionColor,
case
when OptionColor not in ('RED', 'BLUE', 'GREEN') then OriginalColor
when Result_Column > 1 then OriginalColor
else OptionColor end as Result_Column
from (
select i.Invoice, i.OriginalColor, i.OptionColor,
(select count(distinct OptionColor) from table ic where ic.Invoice = i.Invoice) as Result_Column
from table i
) temp