SQL:内部联接,前两行,第二个表来自条件

时间:2013-04-19 09:49:03

标签: sql join conditional-statements

您好我正在尝试加入2个表,只有第二个表连接的第2行连接到第一个表。

例如,我有以下2个表:

**Table A**
Column1 |   Column2 |   Column3
A       |   B       |   30
A       |   C       |   50
A       |   D       |   25

**Table B**
Column4 |   Column5
B       |   35  
B       |   90
B       |   65
B       |   80
B       |   85
B       |   40
C       |   100
C       |   60
C       |   70
C       |   65

以下是我的常规查询示例:

select *
from 
    (
        select * 
        from A 
        where Column1 = 'A' and (Column2 = 'B' or Column2 = 'C') 
        order by Column2, Column3
    ) A
    inner join
    (
        select * 
        from B 
        where (Column4 = 'B' or Column4 = 'C') 
        order by Column5
    ) B
    on (A.Column2 = B.Column4 and ((B.Column5 - A.Column3) > 30))

结果应如下所示:

**Result:**
Column1   |   Column2 |   Column3 |   Column4 |   Column5 
A         |   B       |   30      |   B       |   65
A         |   B       |   30      |   B       |   80 
A         |   B       |   30      |   B       |   85 
A         |   B       |   30      |   B       |   90
A         |   C       |   50      |   C       |   100

但是,我想要的结果只是从第二个表结果中仅加入2行。预期结果应为:

**Expected Result:**
Column1   |   Column2 |   Column3 |   Column4 |   Column5
A         |   B       |   30      |   B       |   65
A         |   B       |   30      |   B       |   80
A         |   C       |   50      |   C       |   100

有没有人知道如何创建这样的sql语句?谢谢。

3 个答案:

答案 0 :(得分:0)

一个好的开始是在没有内联视图的情况下编写更简单的SQL:

select *
from   A inner join
       B on (A.Column2 = B.Column4)    
where  A.Column1 = 'A'               and
       A.Column2 in ('B','C')        and
       (B.Column5 - A.Column3) > 30)

答案 1 :(得分:0)

您可以使用row_number()来限制行数。该示例假定(Column1, Column2, Column3)是唯一的。如果表A有主键,请改用它。

select  *
from    (
        select  Column1
        ,       Column2
        ,       Column3
        ,       Column4
        ,       Column5
        ,       row_number() over (partition by Column1, Column2, Column3 
                                   order by Column5 - Column3 desc) as rn
        from    A
        join    B
        on      A.Column2 = B.Column4
        where   Column1 = 'A' 
                and Column2 in ('B', 'C')
                and Column5 - Column3 > 30
        ) SubQueryAlias
where   rn < 2

See example at SQL Fiddle.

答案 2 :(得分:0)

尝试使用CTE

WITH Top2Rows AS (
    SELECT TOP 2 *
    FROM TableB
    WHERE ([ADD CONSTRAINTS])
)

SELECT *
FROM TableA a
JOIN Top2Rows r ON a.ID = b.ID
WHERE ([ADD CONSTRAINTS])