簡體   English   中英

基於同一表的另一列值選擇帶列的語句

[英]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值基於以下條件

  1. 可用的選項只有紅色,綠色和藍色3種顏色。
  2. 如果發票中的所有Option_Colors均為綠色,則結果列將為GREEN。
  3. 如果發票中的所有Option_Colors均為藍色,則結果列將為BLUE

  4. 如果發票中的所有Option_Colors均為紅色,則結果列將為紅色

  5. 如果發票的Option_Colors中混合了顏色,則顯示的顏色為Original_Color列。

    1. 如果Option_Colors不是RED,GREEN或BLUE,則顯示的顏色為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM