仅在上面的现有行结果上

时间:2015-08-11 09:08:01

标签: sql sql-server sql-server-2008 tsql

我正在尝试从查询中返回结果,其中WHERE考虑了当前行上方行中返回的值。

在下面的示例查询中,如果已经在主SELECT的前一行中返回了TableC.Colb中的值,我想将其从OUTER APPLY中排除并转到下一行行ColA > Col1

Select TableA.Col1, TableA.Col2, TableC.Colb

From
(Select x.Col1, X.Col2  From (values(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E'), (6, 'F')) as X(Col1, Col2)) as TableA


Outer Apply
(Select min(TableB.Colb) as Colb
From (Select x.ColA, X.ColB  From (values (1, 'H'), (4,'V'), (5,'W'), (6,'X'), (7,'Y'), (8,'Z')) as X(ColA, Colb)) as TableB
Where Tableb.ColA > TableA.Col1
) as TableC

目前的结果是:

enter image description here

我想要达到的结果是:

enter image description here

2 个答案:

答案 0 :(得分:0)

此代码的问题在于没有足够的标识符将两个表绑定在一起,并且where子句Tableb.ColA > TableA.Col1对于第二个表上的第一个值和第一个表上的前三个值都为true。我建议在这两个表之间建立直接关系,或者在行号上加入LEFT JOIN CLAUSE。

Select TableA.Col1, TableA.Col2, TableC.Colb

From
(Select ROW_NUMBER() over (order by x.Col1) AS 'ColNum', x.Col1, X.Col2  From (values(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E'), (6, 'F')) as X(Col1, Col2)) as TableA


LEFT JOIN
(Select ROW_NUMBER() over (order by TableB.ColA) AS ColA, TableB.ColB
From (Select x.ColA, X.ColB  From (values(4,'V'), (5,'W'), (6,'X'), (7,'Y'), (8,'Z')) as X(ColA, Colb)) as TableB) AS TableC ON TableC.ColA = TableA.ColNum

答案 1 :(得分:0)

您可以对TableATableB以及LEFT JOIN上的行进行编号:

WITH    TableA
    AS ( SELECT x.Col1 ,
                X.Col2 , 
                ROW_NUMBER() OVER (ORDER BY X.Col2) rw
        FROM    ( VALUES ( 1, 'A'), ( 2, 'B'), ( 3, 'C'), ( 4, 'D'), ( 5, 'E'), ( 6, 'F') ) AS X ( Col1, Col2 )
        ),
TableB
    AS ( SELECT x.ColA ,
                X.ColB , 
                ROW_NUMBER() OVER (ORDER BY X.ColB) rw
        FROM    ( VALUES ( 4, 'V'), ( 5, 'W'), ( 6, 'X'), ( 7, 'Y'), ( 8, 'Z') ) AS X ( ColA, Colb )
        )
SELECT  TableA.Col1 ,
        TableA.Col2 ,
        TableB.Colb
FROM    TableA
        LEFT JOIN TableB 
            ON TableA.rw = TableB.rw

这会产生您需要的结果。