如何在sql查询中使用不存在的列

时间:2018-05-29 17:17:46

标签: sql sql-server sql-server-2012

我在SQL Server 2012中工作。我必须写一个sql语句,我首先为[Pay_Type]赋值,这是一个不存在的列(不确定它是否可以作为变量调用)和基于它的值我想在另一个case语句中使用它,如下所示

SELECT sp.First_Name, [Pay_Type] = CASE WHEN NOT EXISTS(SELECT '1' FROM 
PERSON_SALARY ps WHERE ps.PARTY_ID = sp.PARTY_ID and ps.END_DATE IS NULL) 
THEN 'Hourly' ELSE 'Salary' END,
HOURLY_RATE = CASE WHEN [Pay_Type] = 'Hourly' THEN pj.HOURLY_RATE ELSE 
'0.00' END
FROM SEC_PERSON sp 
LEFT OUTER JOIN PERSON_JOB pj ON sp.PERSON_ID = pj.PERSON_ID 
WHERE sp.END_DATE IS NOT NULL

但是我收到“无效的列名'Pay_Type'”错误。

1 个答案:

答案 0 :(得分:0)

列别名不能在它们定义的同一SELECT中重复使用。典型的答案是使用子查询或CTE。我也喜欢使用横向连接:

SELECT sp.First_Name, s.Pay_Type,
       HOURLY_RATE = (CASE WHEN s.Pay_Type = 'Hourly' THEN pj.HOURLY_RATE ELSE 
'0.00' END)
FROM SEC_PERSON sp LEFT OUTER JOIN
     PERSON_JOB pj
     ON sp.PERSON_ID = pj.PERSON_ID OUTER APPLY
     (SELECT (CASE WHEN NOT EXISTS (SELECT 1
                                    FROM PERSON_SALARY ps
                                    WHERE ps.PARTY_ID = sp.PARTY_ID and ps.END_DATE IS NULL
                                   ) 
                   THEN 'Hourly' ELSE 'Salary'
             END) as PayType
     ) s    
WHERE sp.END_DATE IS NOT NULL