如何将CASE语句中的SELECT语句连接到外部查询?

时间:2014-02-04 22:04:34

标签: sql sql-server-2008 join case-statement

在下面我需要以某种方式将case语句中的字段与外部表连接起来,以便为当前的PK和CIA值选择fldNumb。我真的被困了,有人可以帮忙吗?

INSERT INTO #CTE (sMedNum)
        SELECT T1.sMedNum
        FROM #CTE INNER JOIN
            (SELECT
                (CASE WHEN (Charindex('.', CAST(rInd AS NVARCHAR(30))) > 0) 
                    THEN CAST(( SELECT fldNumb 
                                FROM #CTE 
                                WHERE sCtr = FLOOR(rInd)) AS FLOAT) + 
                         CAST(( SELECT fldNumb
                                FROM #CTE 
                                WHERE Ind = FLOOR(rInd+1)) AS FLOAT) / 2                     
                    ELSE CAST(( SELECT fldNumb 
                                FROM #CTE 
                                WHERE sCtr = rInd) AS FLOAT)
                END) AS sMedNum, fldPK, fldCIA
            ) T1
            ON 
            #CTE.fldPK = T2.fldPK AND
            #CTE.fldCIA = T2.fldCIA

1 个答案:

答案 0 :(得分:1)

没有您的数据库我无法帮助您,但看起来您需要对表进行别名。如果您试图从子查询外的表中获取值,则必须将其称为不同的值。

这是一个例子

  select case 
    when a1.value = 1 then (select a2.id from tableA a2 where a1.val2 = a2.val2)
    when a1.value = 2 then (select a3.id from tableA a3 where a1.val2 = a3.val2)
    when a1.value = 3 then (select a4.id from tableA a4 where a1.val2 = a4.val2)
  end as new_id
  from tableA a1

希望这是有道理的,如果没有,那么这就是问题所在;)