计算新变量

时间:2018-12-12 21:26:42

标签: sql-server

我有以下代码,并希望创建一个结果列,该列计算FCT_MAX_CHARGES和CPT_MAX_CHARGES变量之间的差。我正在寻找将在下表中产生CPT_FCT DELTA列的代码。

USE EMTCQIData

SELECT CONC.[ID Number] as FIN, CONC.table,

   CASE
          WHEN CONC.table like '%level 5%' THEN '99285' 
          WHEN CONC.table like '%level 4%' THEN '99284'

   END FCT_MAX,

   CASE
          WHEN CONC.table like '%level 5%' THEN $200 
          WHEN CONC.table like '%level 4%' THEN $100

   END FCT_MAX_CHARGES,

   CPT.CPT,

   CASE
          WHEN CPT.CPT like '99285%' THEN $200
          WHEN CPT.CPT like '99284' THEN $100

   END CPT_MAX_CHARGES

FROM CPT_MASTER as CPT 


                          Expected Results
ID | FCT_MAX| FCT_MAX_CHARGGES| CPT   | CPT_MAX_CHARGES| CPT_FCT DELTA
 1    99284     200             99284       100              100

2 个答案:

答案 0 :(得分:1)

您不能在相同作用域的另一个表达式中引用别名,但是解决该问题的一种方法是在另一个级别执行第一组表达式,例如CTE或子查询:

;WITH cte AS
(
  SELECT 
    CONC.[ID Number] as FIN, 
    CONC.table,
    CASE
      WHEN CONC.table like '%level 5%' THEN '99285' 
      WHEN CONC.table like '%level 4%' THEN '99284'
    END AS FCT_MAX,
    CASE
      WHEN CONC.table like '%level 5%' THEN $200 
      WHEN CONC.table like '%level 4%' THEN $100
   END AS FCT_MAX_CHARGES,
   CPT.CPT,
   CASE
     WHEN CPT.CPT like '99285%' THEN $200
     WHEN CPT.CPT like '99284' THEN $100
   END AS CPT_MAX_CHARGES
   FROM CPT_MASTER as CPT
)
SELECT 
  FIN,
  [table],
  FCT_MAX,
  CPT,
  FCT_MAX_CHARGES,
  CPT_MAX_CHARGES,
  CPT_FCT DELTA = FCT_MAX_CHARGES - CPT_MAX_CHARGES
FROM cte;

答案 1 :(得分:0)

这实际上非常简单,以下代码可以工作:

SELECT FIN, Clinical, FCT_MAX, FCT_MAX_CHARGES, CPT, CPT_CHARGES, (FCT_MAX_CHARGES - CPT_CHARGES) AS DELTA