从两个不同的表中选择不同的记录

时间:2018-10-17 12:04:17

标签: sql join left-join teradata

我有两个数据库:

Account Number:    Days Opened:
1                  3
2                  10
3                  30
4                  17

Account Number:    Company:   Transaction Date:
1                  ABC        1-1-1990
1                  ABC        2-1-1990
1                  ABC        3-1-1990
2                  DEF        10-2-1991
2                  DEF        11-2-1992
3                  GHI        20-3-1993

如何获取返回以下内容的信息(仅查看未满二十天的帐户):

Account Number:    Days Opened:   Company:
1                  3              ABC
2                  10             DEF
4                  17             ?

每当我尝试使用左联接时,它返回的记录都比我想要的多。

4 个答案:

答案 0 :(得分:0)

尝试使用内部联接和独特

select distinct t1.accountno,t1.daysopened,t2.Company from table1 t1 left join table2 t2
on t1.accountno=t2.accountno
and DaysOpened<20

答案 1 :(得分:0)

您的数据结构混乱。公司不应该在交易表中。您应该在第一张表中查找它。

Teradata中的一种方法使用qualify

select t1.accountno, t1.daysopened, t2.company
from table1 t1 join
     table2 t2
     on t1.acountno = t2.accountno
where t1.daysopened < 20
qualify row_number() over (partition by t2.accountno order by t2.transaction_date desc) = 1;

答案 2 :(得分:0)

您可以使用group by,因此您只返回唯一的组合:

sel a.account_number
, a.days_opened
, c.company
from accounts a
inner join companies c
on a.account_number = c.account_number
where a.days_opened < 20
group by 1,2,3

如果要为公司表中不存在的帐号留空行,也可以使用左联接。但是,看到潜在的结果,我认为您需要一个内在的联系。

答案 3 :(得分:0)

像您一样创建表。

CREATE TABLE table1
    ([AccountId] Int, [DaysOpened] Int)
;

INSERT INTO table1
    ([AccountId], [DaysOpened])
VALUES
    (1, 3),
    (2,10),
    (3,30),
    (4,17);

CREATE TABLE table2
    ([AccountId] Int, [Company] varchar(50),[TransactionDate] date)
;

INSERT INTO table2
    ([AccountId], [Company],[TransactionDate])
VALUES
    (1, 'ABC','1-1-1990'),
    (1, 'ABC','2-1-1990'),
    (1, 'ABC','3-2-1990'),
    (2, 'DEF','10-2-1990'),
    (3, 'GHI','20-3-1990'); 

并尝试使用此脚本。

select t1.AccountId,t1.DaysOpened,t2.Company from table1 t1
left join table2 t2 ON t1.AccountId=t2.AccountId
where DaysOpened < 20
Group by t1.AccountId,t1.DaysOpened,t2.Company

您可以尝试使用此link

相关问题