2017-07-31 27 views
0

我試圖找到所有已經提到過多次的所有租戶的full_nameemail_idphone numberreferral code。有2個表,我試圖獲得兩次以上的數據。我的代碼沒有錯誤的跡象,但在運行查詢其給我的錯誤如何將計數組合與從哪裏得到2個表格的結果

聚合不應出現在WHERE子句中,除非它是包含在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) 

回答

2

在子選擇,你應該使用具有過濾彙總值

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 
    ) 
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一個不同的名稱。
  • 與任何對dbo.Referrals
+0

問題的唯一鍵字段替換READ_BELOW: - 是否推薦表已PROFILE_ID? - 對於由同一人推薦的兩行,它是否具有相同的referrer_id值或不同值?- dbo_referrals的主要關鍵是什麼? – dev

+0

profileid與引薦ID相同,它們是相同的 –

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 
相關問題