使用Case Expression在带SQL的派生列中交叉应用

时间:2016-09-29 12:57:30

标签: sql sql-server tsql

我的查询非常简单,只有很少的计算列,如

SELECT COL1 , COL2,COL3
COL4 = (COL1-(COL2*.15))
COL5 = (COL3*(COL1*1.5))

FROM TABLE1 AS A 
INNER JOIN TABLE2 AS B
ON A.ID = B.ID

现在我尝试使用交叉应用

将Case语句放在计算列值上
CROSS APPLY (

SELECT REMARKS = CASE WHEN COL4> COL1 THEN GOOD ELSE BAD END

但这是错误的。

在输出中我期待所有列,即col1,col2,col3,col4,col5,备注

有人可以建议我的错误是什么吗?

4 个答案:

答案 0 :(得分:2)

问题是CROSS APPLY无法从SELECT子句访问计算字段,因为它首先被评估。

一个选项是为每列使用一个CROSS APPLY级联计算列:

SELECT COL1, COL2, COL3,
       C.COL4, D.COL5,
       E.REMARKS 
FROM TABLE1 AS A 
INNER JOIN TABLE2 AS B ON A.ID = B.ID
CROSS APPLY (SELECT COL4 = (COL1-(COL2*.15))) AS C
CROSS APPLY (SELECT COL5 = (COL3*(COL1*1.5))) AS D
CROSS APPLY (SELECT REMARKS = CASE WHEN C.COL4 > COL1 THEN 'GOOD' ELSE 'BAD' END) AS E

Demo here

答案 1 :(得分:1)

这个怎么样?

{{1}}

答案 2 :(得分:0)

将您的第一个脚本包含在select语句中,然后执行交叉应用

SELECT * FROM (SELECT COL1 , COL2,COL3
                ,COL4 = (COL1-(COL2*.15))
                ,COL5 = (COL3*(COL1*1.5)) 

FROM TABLE1 AS A 
INNER JOIN TABLE2 AS B
ON A.ID = B.ID )t

CROSS APPLY

(
SELECT  CASE WHEN t.COL4 > t.COL1 THEN 'GOOD' ELSE 'BAD' END REMARKS
) t1

答案 3 :(得分:0)

Select x.Iss_Carat,x.Rec_Carat,x.REMARKS from Process_Issue_Receive PTR
cross apply( SELECT *, REMARKS = CASE WHEN Rec_Carat> Iss_Carat THEN 'GOOD' 
                                ELSE 'BAD' 
                                END FROM LAB_Issue_Receive LIR where ptr.Lot_Key = LIR.Lot_key)x where x.REMARKS = 'GOOD'

使用2个差异表

尝试此查询