SQL Server:使用select case中的值

时间:2016-12-28 09:30:35

标签: sql-server tsql

我想知道是否有办法在同一个select中使用case语句返回的值?

这将是这样的:

SELECT
    id,
    name,
    firstValue,
    secondValue,
    CASE 
       WHEN fistValue > secondValue 
          THEN firstValue 
       ELSE SecondValue 
    END as Value,
    CASE 
       WHEN value > 5 
          THEN 'something' 
    END
FROM 
    SomeTable

但这会导致值的列名无效。

4 个答案:

答案 0 :(得分:2)

;with cteSomeValues as
(
Select 
        id,
        name,
        firstValue,
        secondValue,
        CASE WHEN fistValue > secondValue THEN firstValue ELSE SecondValue END as Value
        FROM SomeTable
)
Select 
        id,
        name,
        firstValue,
        secondValue,
        Value,
        CASE WHEN value > 5 then 'something' END
FROM cteSomeValues

答案 1 :(得分:1)

试试这个

;WITH CTE AS(
Select 
id,name,firstValue,secondValue,
(CASE WHEN fistValue > secondValue THEN firstValue ELSE SecondValue END) as Value,
FROM SomeTable
) select  id, name, firstValue,secondValue,case when value > 5 then 'something'  END as VALUECOLUMN from cte

答案 2 :(得分:0)

你必须把两个案件放在一起。

Field field = Application.ActiveDocument.Fields.Add(Application.Selection.Range, WdFieldType.wdFieldLink, LinkText);

if (field != null) {
    field.Update();
}

答案 3 :(得分:0)

另一种解决方法是这样做。

select t.id, 
       t.Name, 
       t.firstvalue, 
       t.secondvalue, 
       case
         when t.value = 5 then 'something' 
       end
from ( SELECT id,
              name,
              firstValue,
              secondValue,
              CASE 
                WHEN fistValue > secondValue THEN firstValue 
                ELSE SecondValue 
              END as Value
       FROM   SomeTable
     ) t