0

我正在尝试构建一个查询,它将为我提供唯一的行。细节:-

Table 1 (F1, F2 are the columns)
F1  F2
1   A1
2   A2
3   A3
4   A4

Table 2 (F3,F4 are the columns)
F3  F4
1   B1
1   B11
2   B2
2   B22

我的查询(不正确)
select rrn(A), F1,F2,F3,F4 from rush2hem1.T1 A left outer join rush2hem1.T2 B on A.F1=B.F3

这给了我下面的输出,这不是我想要的: -

RRN F1  F2  F3  F4
1   1   A1 1    B1 
1   1   A1 1    B11 
2   2   A2 2    B2 
2   2   A2 2    B22 
3   3   A3 (null)   (null)
4   4   A4 (null)   (null)

我正在构建查询的预期输出是:-

RRN F1  F2  F3  F4
1   1   A1 1    B1 
2   2   A2 2    B2 
3   3   A3 (null)   (null)
4   4   A4 (null)   (null)

如果您有任何建议,请告诉我。

4

3 回答 3

2

这个问题可以在不同的 RDBMS 中以不同的方式解决。在任何情况下,您都必须指定Table2要从哪条记录中获取(按order by子句)

如果你的数据库有窗口函数row_number(),你可以像这样使用它:

select
    F1, F2, F3, F4
from (
    select
        T1.F1, T1.F2, T2.F3, T2.F4,
        -- order by specifying which row you would get from Table2
        row_number() over(partition by T1.F1 order by T2.F4) as rn
    from Table1 as T1
        left outer join Table2 as T2 on T2.F3 = T1.F1
) as cte  
where rn = 1;

在 SQL Server 中,您可以使用outer apply

select
    T1.F1, T1.F2, T2.F3, T2.F4
from Table1 as T1
    outer apply (
        select top 1 T2.F3, T2.F4
        from Table2 as T2
        where T2.F3 = T1.F1
        order by T2.F3 asc   -- This is important line
    ) as T2;

在 PostgreSQL 中,您可以使用distinct on语法:

select distinct on (T1.F1)
    T1.F1, T1.F2, T2.F3, T2.F4
from Table1 as T1
    left outer join Table2 as T2 on T2.F3 = T1.F1
order by T1.F1, T2.F4; -- sort by F4 is important
于 2013-09-07T10:00:52.613 回答
1

未经测试,它是 SQL server 版本。

select rrn(A), F1,F2,F3,F4
from
(
 select rrn(A), F1,F2,F3,F4,row_number() over(partition by RRN order by RRN) as rn
from rush2hem1.T1 A left outer join rush2hem1.T2 B 
on A.F1=B.F3
) as dt
where dt.rn = 1
于 2013-09-07T03:59:49.987 回答
0

请检查结果OUTER APPLY

SELECT 
    * 
FROM 
    Table1 a
OUTER APPLY 
    (SELECT 
        TOP 1 * 
    FROM 
        Table2 b 
    WHERE a.F1=b.F3)c
于 2013-09-07T04:32:44.397 回答