日期:2014-05-18  浏览次数:20505 次

一个表中的字段是另一个表中数据的计算结果,该怎么查询
问题不好描述,不好意思

假如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 @A
select 1,23,43,87 union all
select 2,45,65,76 union all
select 3,25,65,87
declare @B table (id int,x int,k varchar(7))
insert into @B
select 1,23,'[y]/[z]' union all
select 2,45,'[z]' union all
select 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)
    end
from @B a

/*
id          x           k
----------- ----------- ---------------------------------------
1           23          0.4942528735632
2           45          76.0000000000000
3           25          5655.0000000000000
*/