Sql 我想要一个查询从表2中选择4个以上重复的AccountId,在表1中有不同的名称

Sql 我想要一个查询从表2中选择4个以上重复的AccountId,在表1中有不同的名称,sql,select,Sql,Select,我需要一个查询,从表2中选择4个以上重复的AccountId,并在table1 以下是表格结构: table1 | Table2 ID AccountNumber Name | ID AccountNumber AccountID 1 12345 John Jeff | 1 12345 A467T 1

我需要一个查询,从表2中选择4个以上重复的AccountId,并在
table1

以下是表格结构:

table1                             |       Table2
ID   AccountNumber  Name           |       ID       AccountNumber AccountID
1     12345         John Jeff      |        1          12345        A467T
1     12345         Patrick Jones  |        1          12345        A467T
ID
AccountNumber
在两个表中都是相同的

  • 表1有一个名称
  • 表2有AccountID

这里有一个查询,用于查找具有4个以上不同名称的AccountID:

select  t2.AccountID
from    Table1 as t1
join    Table2 as t2
on      t1.AccountNumber = t2.AccountNumber
        and t1.ID = t2.ID
group by
        t2.AccountID
having  count(distinct t1.Name) > 4
如果这不是你想要的,请澄清问题!例如,您可以添加所需的输出

编辑:在回复您的评论时,您可以使用子查询查询ID和编号:

select  distinct 
        ID
,       AccountNumber
,       AccoutnID
from    Table2
where   AccountNumber in 
        (
        ... place query from above here ...
        )

谢谢Andomar,它正在工作,但是如果我想让AccountNumber和ID也作为输出的一部分呢?如果每个AccountNumber只有一个AccountID,您可以
按t2.AccountID,t2.AccountNumber,t2.ID分组,然后选择所有三列。@Bayo Alen:那么您必须返回表2来计算ID。。。一种方法是子查询,添加了示例。