同一个表的字段相减的问题
一个表A的结构如图所示:
现在想让int_id为1的value值减去int_id为2的value值,且两个相减的value对应的f_id相等,请问怎么用sql语句表示?
------最佳解决方案--------------------
SELECT fid,value
FROM a
WHERE ini_id=1
UNION ALL
SELECT fid,-1*value
FROM a
WHERE ini_id=2
------其他解决方案--------------------
select a.value-b.value from A a where a.int_id=1
and exists (select top(1) 1 from A b where a.fid=b.fid and b.int_id=2)
------其他解决方案--------------------刷了半天总算看到图了.
你这个同一fid的 int_id为1和2的有多个,是用和来相减吗?
------其他解决方案--------------------少了个from,哥,你的代码能不能别那么有创意啊
SELECT ( ( SELECT CAST(value AS INT)
FROM param a
) - ( SELECT CAST(value AS INT)
FROM param b
) )
FROM ( SELECT fid ,
value
FROM param
WHERE int_id = 1
) a
INNER JOIN ( SELECT fid ,
value
FROM param
WHERE int_id = 2
) b ON a.fid = b.fid
------其他解决方案--------------------图在何处 ?
------其他解决方案--------------------晴天大大,你网速有问题,我能看到图
------其他解决方案--------------------这样?
select int_id,fid,sum(case when int_id=1 then value else -value end)as v from tb group by int_id,fid
------其他解决方案--------------------这里value是varchar类型 但是这样还会报错
select ((select CAST(value as int) from param a) - (select CAST(value as int) from param b)) (select fid,value from param where int_id=1) a inner join(select fid,value from param where int_id=2) b on a.fid=b.fid