SQL Server 2008 - 根据WHERE语句中的条件返回新列中的文本字符串

时间:2013-09-20 21:26:42

标签: sql sql-server sql-server-2008-r2 where where-clause

select PERSONNUM, PAYCODENAME as StraightTime, PAYCODENAME as OT
from dbo.VP_ALLTOTALS
where OT in ('Overtime', 'Double Overtime') 
return 'OT',
and StraightTime in ('Straight Time Earnings', 'Sunday Premium')
return 'Straight Time'

2 个答案:

答案 0 :(得分:0)

其中子句只是过滤器...使用case语句将逻辑放入选择行。

select PERSONNUM, PAYCODENAME as StraightTime, PAYCODENAME as OT
case when OT in ('Overtime', 'Double Overtime')  then 'OT',
when StraightTime in ('Straight Time Earnings', 'Sunday Premium') then 'Straight Time'
else 'not in list?' end as 'returnedcode' --name your new column here
from dbo.VP_ALLTOTALS

答案 1 :(得分:0)

我认为您正在寻找CASE

SELECT CASE 
         WHEN ot IN ( 'Overtime', 'Double Overtime' ) THEN ot 
         WHEN straighttime IN ( 'Straight Time Earnings', 'Sunday Premium' ) 
            THEN straighttime 
         ELSE NULL 
       END AS ColumnName 
FROM   dbo.vp_alltotals 

Demo

或者,如果您只想返回字符串OR / Straight Time

 SELECT CASE 
         WHEN ot IN ( 'Overtime', 'Double Overtime' ) THEN 'OT'
         WHEN straighttime IN ( 'Straight Time Earnings', 'Sunday Premium' ) 
            THEN 'straighttime' 
         ELSE NULL 
       END AS Type
FROM   dbo.vp_alltotals 

Demo