2016-07-14 40 views
0

如果应该从case-statement中“提取”列,是否可以引用表中的列?TSQL:引用具有case语句的列

update t1 
set col1 = value 
from table1 t1, (select Col3, Col4 from table1) t2 
where t1.(CASE 
      WHEN Col3 > 0 THEN Col1 
      ELSE Col2) = t2.(CASE WHEN Col3 > 0 
            THEN Col1 
            ELSE Col2 
           END) 

在此先感谢您的帮助!

+0

另外:[This](http://stackoverflow.com/a/1599201/92546)答案提供了几个理由考虑使用更现代的'JOIN'语法。 – HABO

回答

0

你可以在一个case语句等指与表的别名列名,

update t1 
set t1.col1 = value 
from table1 t1, (select Col3, Col4 from table1) t2 
where CASE 
     WHEN t1.Col3 > 0 THEN t1.Col1 
     ELSE t1.Col2 
     END = CASE WHEN t2.Col3 > 0 
       THEN t2.Col1 
       ELSE t2.Col2 
      END 

报表进行评估,然后再进行比较的情况。

+0

此解决方案对我无效,因为我也在t2中使用“group by”,并且无法添加某些列。没有另外一种方式来做这件事吗? – bpesunny

+0

你应该提出适当的/完整的细节,以便你能得到有效的解决方案。在派生查询中使用group by不会影响外部条件! –