如何在Select语句中调用计算字段

时间:2014-04-29 10:07:27

标签: sql sql-server database tsql

请提前帮助我帮助我如何在下面显示的案例陈述中使用'os'

select col1,col2, (col3+1) as os,
CASE 
      WHEN CONVERT(date,GETDATE(),103) <=@duedt1  THEN          
        os
      else '0'    
END as 'ot1',
CASE 
      WHEN CONVERT(date,GETDATE(),103) >@duedt1  THEN       
        os
      else '0'    
END as 'ot2'
from t1

4 个答案:

答案 0 :(得分:0)

select col1,col2,
CASE 
      WHEN CONVERT(date,GETDATE(),103) <=@duedt1  THEN          
        (col3+1)
      else '0'    
END as 'ot1',
CASE 
      WHEN CONVERT(date,GETDATE(),103) >@duedt1  THEN       
        (col3+1)
      else '0'    
END as 'ot2'
from t1

答案 1 :(得分:0)

您可以使用CTE等,或者您也需要将表达式放在此处。如果您在此查询中创建计算列,则无法在此任何其他表达式中使用它。

;WITH cte_os
AS
(
    SELECT col1, col2, col3+1 [os] FROM t1
)
SELECT col1, col2, os, CASE WHEN `x (lazy)` THEN os ELSE 0 END ot1,.....
FROM cte_os

答案 2 :(得分:0)

您需要子查询

SELECT col1,col2,CASE 
                     WHEN CONVERT(date,GETDATE(),103) <=@duedt1 
                     THEN  os
                     ELSE '0'    
                 END as 'ot1',
                 CASE 
                     WHEN CONVERT(date,GETDATE(),103) >@duedt1  
                     THEN os
                     ELSE '0'    
                 END as 'ot2'
FROM (
      select col1,col2, (col3+1) as os
      from t1
     )Z

答案 3 :(得分:0)

您也可以使用CROSS APPLY。

select col1,col2, os,
CASE 
      WHEN CONVERT(date,GETDATE(),103) <=@duedt1  THEN          
        os
      else '0'    
END as 'ot1',
CASE 
      WHEN CONVERT(date,GETDATE(),103) >@duedt1  THEN       
        os
      else '0'    
END as 'ot2'
from t1
    CROSS APPLY (SELECT col3 + 1 os) t2