如何将计数组与从2个表中获取结果的位置组合在一起

时间:2017-07-31 19:26:20

标签: sql sql-server

我正在尝试查找所有不止一次推荐的所有租户的full_nameemail_idphone numberreferral code。有2个表,我正在尝试获取两次以上的数据。我的代码没有错误信号,但在运行查询时会给我错误

  

聚合可能不会出现在WHERE子句中,除非它在a中   包含在HAVING子句或选择列表中的子查询以及列   被聚合是一个外部参考。

select dbo.Profiles.first_name + ' ' + dbo.Profiles.last_name as full_name,dbo.Profiles.email, dbo.Profiles.phone ,dbo.Profiles.referral_code  from dbo.Profiles 
where profile_id = (select referrer_id from dbo.Referrals where COUNT(referrer_id)>2 group by dbo.Referrals.referrer_id)

3 个答案:

答案 0 :(得分:2)

在subselect中,您应该使用过滤器聚合值

  select 
      dbo.Profiles.first_name + ' ' + dbo.Profiles.last_name as full_name
      ,dbo.Profiles.email
      , dbo.Profiles.phone
      ,dbo.Profiles.referral_code  
  from dbo.Profiles 
  where profile_id = ( 
        select referrer_id 
        from dbo.Referrals 
        group by dbo.Referrals.referrer_id
         HAVING COUNT(referrer_id)>2 
    )

答案 1 :(得分:0)

select dbo.Profiles.first_name + ' ' + dbo.Profiles.last_name as 
full_name,dbo.Profiles.email, dbo.Profiles.phone ,dbo.Profiles.referral_code  
from dbo.Profiles 
where profile_id = 
(select referrer_id from dbo.Referrals 
  group by dbo.Referrals.referrer_id
  having COUNT(READ_BELOW)>2
) 
  • 我假设referrer_id是profile_id的另一个名称。
  • 将READ_BELOW替换为dbo.Referrals
  • 的唯一键字段

答案 2 :(得分:0)

SELECT referrer_id, COUNT(*) AS 'Count_'
INTO  #RefCount
FROM dbo.Referrals
GROUP BY referrer_id

SELECT dbo.Profiles.first_name + ' ' + dbo.Profiles.last_name AS 'Full_Name', 
dbo.Profiles.email, dbo.Profiles.phone ,dbo.Profiles.referral_code  
FROM dbo.Profiles, #RefCount RC 
WHERE dbo.Profiles.profile_id = RC.referrer_id
AND RC.Count_ > 2