日期:2014-05-19  浏览次数:20520 次

这样的要求用sql可以实现吗?
表1:
    指标代码                                           数量
      ak3000                                   20


表2:
        指标名                                                     数量
        [ak3000]指标                                       30

我想要做的是:
        首先将表2中的指标名改为                 指标代码       指标名
                        即   [ak3000]指标                   ak3000         指标
然后
得到表1和表2对应项的差值

------解决方案--------------------
Create Table 表1
(指标代码 Varchar(10),
数量 Int)
Insert 表1 Select 'ak3000 ', 20

Create Table 表2
(指标名 Nvarchar(10),
数量 Int)
Insert 表2 Select N '[ak3000]指标 ', 30
GO
Select
B.指标代码,
B.指标名,
B.数量 - A.数量 As 差值
From
表1 A
Inner Join
(Select
Substring(指标名, 2, CharIndex( '] ', 指标名) - 2) As 指标代码,
Stuff(指标名, 1, CharIndex( '] ', 指标名), ' ') As 指标名,
数量
From 表2) B
On A.指标代码 = B.指标代码
GO
Drop Table 表1, 表2
--Result
/*
指标代码 指标名 差值
ak3000 指标 10
*/
------解决方案--------------------
可以把表一加上[]及指标。
select b.*,b.数量-a.数量 as 差值 from 表2 b inner join
(
select 数量, '[ '+指标代码+ '] '+ '指标 ' as 指标名 from 表1
) a on b.指标名=a.指标名

------解决方案--------------------
select b.指标代码,
substr(b.指标名,charindex(b.指标名, '] ')+1) as 指标名,
(b.数量-a.数量) as 数量
from 表1 a,表2 b
where b.指标代码=substr(b.指标名,2,charindex(b.指标名, '] ')-2)