0

我有两个视图,其中包含以下数据:

查看下限

6
13
19

查看上行

3
9
14

我想使用上面的两个视图生成这个结果

3
4
5

即 6 - 3 = 3、13 -9 =4 和 19-14 =15。

我试过了

 Select l.val - u.val from lowbound l, upbound u;

但这是它的结果

3
10
16
-3
4
10
-8
-1
5
4

2 回答 2

2

所以看起来你需要加入 view1 中的最低数字和 view2 中的最低数字,依此类推。如果您的 DBMS 支持ROW_NUMBER,您可以使用类似

WITH T1
     AS (SELECT V1.val,
                ROW_NUMBER() OVER (ORDER BY val) AS RN
         FROM   View1 V1),
     T2
     AS (SELECT V2.val,
                ROW_NUMBER() OVER (ORDER BY val) AS RN
         FROM   View2 V2)
SELECT T1.val - T2.val
FROM   T1
       JOIN T2
         ON T1.RN = T2.RN

SQL小提琴

于 2013-02-23T10:47:22.257 回答
0

您需要一个存储过程,然后我正在使用 MSSQL 服务器

 BEGIN
 DECLARE lcursor CURSOR
 FOR SELECT * FROM l;
 DECLARE ucursor CURSOR
 FOR SELECT * FROM u;
 DECLARE @l INT;
 DECLARE @u INT;

 FETCH NEXT FROM lcursor 
 INTO @l
 FETCH NEXT FROM ucursor 
 INTO @u

 WHILE @@FETCH_STATUS = 0
 BEGIN
      PRINT @l - @u
      FETCH NEXT FROM lcursor 
      INTO @l
      FETCH NEXT FROM ucursor 
      INTO @u
END
CLOSE lcursor 
DEALLOCATE lcursor 
CLOSE ucursor 
DEALLOCATE ucursor 
END
于 2013-02-23T10:42:57.763 回答