【问题标题】:Select distinct records from two different tables从两个不同的表中选择不同的记录
【发布时间】:2019-03-22 02:37:00
【问题描述】:

我有两个数据库:

帐号: 开设天数: 1 3 2 10 3 30 4 17 帐号: 公司: 交易日期: 1 ABC 1990 年 1 月 1 日 1 ABC 2-1-1990 1 ABC 3-1-1990 2 1991 年 10 月 2 日 2 1992 年 11 月 2 日 3 GHI 20-3-1993

我如何让它返回以下内容(仅查看开立不到 20 天的帐户):

帐号: 开设天数: 公司: 1 3 ABC 2 10 后卫 4 17 ?

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

【问题讨论】:

  • 这是两个,不是数据库。

标签: sql join left-join teradata


【解决方案1】:

你的数据结构搞砸了。公司不应出现在交易表中。您应该查找它——大概在第一个表中。

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】:

试试下面使用内连接和不同的

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

【讨论】:

  • 是否会排除第一个数据库中在第二个表中没有匹配项的所有记录?
  • @klippy,是的,它肯定会 - 你可以在你的数据库中执行它
  • 是否也包括它们?我将编辑我的答案以包含此
  • 能否提供您的预期输出
  • @klippy,我已经修改了我的答案 - 你现在可以检查一下,只需使用左连接和条件在 cluase 上
【解决方案3】:

您可以使用 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

如果您想为公司表中不存在的帐号设置空行,也可以使用左连接。但是,看到您的潜在结果,我认为您需要内部连接。

【讨论】:

    【解决方案4】:

    创建像你一样的表。

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2021-12-08
      • 2023-01-09
      • 2012-09-04
      • 2017-01-26
      相关资源
      最近更新 更多