![](/img/trans.png)
[英]A sql statement, how to copy values in 1 column to another column in that same table
[英]Select statement with column based on another column values of same table
我需要像這樣的選擇語句
select Invoice, Original Color,Product,Option Color, Result_column from table
其中Result_column值基於以下條件
如果發票中的所有Option_Colors均為藍色,則結果列將為BLUE
如果發票中的所有Option_Colors均為紅色,則結果列將為紅色
如果發票的Option_Colors中混合了顏色,則顯示的顏色為Original_Color列。
您可以使用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
你可以試試:
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
嘗試這個。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.