当前位置: 代码迷 >> Sql Server >> 一个表中的字段是另一个表中数据的计算结果,该如何查询
  详细解决方案

一个表中的字段是另一个表中数据的计算结果,该如何查询

热度:10   发布时间:2016-04-27 12:26:42.0
一个表中的字段是另一个表中数据的计算结果,该怎么查询
问题不好描述,不好意思

假如A表如下:
  x y z
1 23 43 87
2 45 65 76
3 25 65 87

B表如下:
  x k
1 23 [y]/[z]
2 45 [z]
3 25 [y]*[z]


如果要查询k的值,该怎么写T-SQL语句啊,如果记录很多,不可能一个个去算呀!

------解决方案--------------------
SQL code
declare @A table (id int,x int,y int,z int)insert into @Aselect 1,23,43,87 union allselect 2,45,65,76 union allselect 3,25,65,87declare @B table (id int,x int,k varchar(7))insert into @Bselect 1,23,'[y]/[z]' union allselect 2,45,'[z]' union allselect 3,25,'[y]*[z]'select id,x,k=    case     when k='[y]/[z]' then (select y*1.00/z from @A where x=a.x)    when k='[z]' then (select z from @A where x=a.x)    when k='[y]*[z]' then (select y*z from @A where x=a.x)    when k='[y]' then (select y from @A where x=a.x)    when k='[y]+[z]' then (select y+z from @A where x=a.x)    when k='[y]-[z]' then (select y-z from @A where x=a.x)    endfrom @B a/*id          x           k----------- ----------- ---------------------------------------1           23          0.49425287356322           45          76.00000000000003           25          5655.0000000000000*/
  相关解决方案