2017-06-16 29 views
0

我有一個問題,我想從表中選擇,但有別名列,每列有一個條件。SQL - 每列都有一個條件

Select Value, Target, Plan from Product 

值爲具有條件:where Product.DetailCode = 'A'列​​,目標必須條件:where Product.DetailCode = 'B', 列Value =Product.Value * 100

編輯:我要像在C#:

if(Product.DetailCode == 'A') {Value = Product.Value * 10} else if(Product.DetailCode == 'B') {Value = Product.Value * 100} 

EDIT2:感謝所有,最後,我有我自己的答案。

select case when product.code = 'A' then product.Value * 10 end as Value, case when product.code = 'B' then product.Value * 100 end as Target from product

非常感謝!

+0

你的問題是? –

+1

怎麼樣'哪裏Product.DetailCode ='A'和Product.DetailCode ='A''?這不行嗎? –

+0

尋找類似於:'Where Product.DetailCode ='A'或Product.DetailCode ='A'' –

回答

0

編輯: 閱讀更改後:

Select 
    if(Product.DetailCode = 'A', value *10, if(Product.DetailCode = 'B', value * 100, value)) AS target 

這將使用值* 10,如果detailcode是,價值* 100,如果detailCode是B和值,如果detailCode是另一回事。

1
Select 
case when Product.DetailCode = 'A' then 100 
    WHEN Product.DetailCode = 'B' then 10 end * Product.Value as value 
    , TARGET 
    , Plan 
from Product 
1

您可以使用此

SELECT 
Value = 
     CASE Product.DetailCode 
     WHEN 'A' THEN Product.Value * 10 
     WHEN 'B' THEN Product.Value * 100 
     ELSE Product.Value * 100 
     END 
, Target, Plan 
FROM Product 
0

考慮創建一個查找表,而不是像硬編碼的條件。查詢可能看起來如下

select p.Value * coalesce(l.koeff,1) Value, Target, Plan 
from Product p 
left join Lookup l on p.DetailCode = l.Code