根据聚合结果显示其他数据

时间:2016-04-28 15:10:50

标签: sql count aggregate sql-server-2014

这是我的第一个问题,我并不知道要使用哪种搜索条件。

无论如何,我在下面的查询中显示了哪些帐户ID在表格中重复以及多少次。此表中还包括firstName,lastname,dob等其他字段。我希望能够根据此查询的结果显示此数据。感谢SQL新手的任何帮助,谢谢!

SELECT accountid, COUNT(AccountId) as Count
from accounts
where RelationshipCode = 'SB'
group by AccountId
HAVING COUNT(AccountId)>1 
order by AccountId

3 个答案:

答案 0 :(得分:0)

select acc.*,
       sub.count
from account acc
     inner join (SELECT accountid, COUNT(AccountId) as Count
                 from accounts
                 where RelationshipCode = 'SB'
                 group by AccountId
                 HAVING COUNT(AccountId)>1) sub on sub.accountid=acc.accountid
order by acc.AccountId

喜欢这个?获取所有重复的帐户?

答案 1 :(得分:0)

SELECT accountid, firstName, lastname,dob,  COUNT(*) as Count  `  
FROM accounts  `  
WHERE RelationshipCode = 'SB'  `  
GROUP BY AccountId,firstName, lastname,dob  `  
HAVING COUNT(*)>1   `  
ORDER BY AccountId`

答案 2 :(得分:0)

具有重复帐户ID的帐户表?哎呀,ID值多少钱呢?你正在寻找重复的权利。删除它们并使ID唯一(可能将其作为表格的主键)。

您的查询已经获得了相关的帐户ID,因此您可以使用它们再次从表格中进行选择:

select *
from accounts
where accountid in
( 
  select accountid
  from accounts
  where relationshipcode = 'SB'
  group by accountid
  having count(*) > 1 
)
order by accountid;

另一种方法是使用COUNT的分析版本,以便只需要读取一次表格:

select *
from
(
  select accounts.*, count(*) over (partition by accountid) as cnt
  from accounts
  where relationshipcode = 'SB'
) counted
where cnt > 1
order by accountid;