2017-09-30 100 views
0

我有五個表。我需要從所有這些數據中獲取數據。表'Tenancy_histories'包含move_in_date,move_out_date,租金列。 'Profiles'包含名字,姓氏,電子郵件,profile_id等。'Referrals'包含referrer_bonus_amount和類似的其他數據。最重要的是,它包含由特定的profile_id所做的推薦數量,這是「referrer_id(與配置文件ID相同)」列中該profile_id的發生次數。 'Employment_details'包含最新的僱主,職業類別子查詢,加入一個查詢

我需要編寫一個查詢來顯示個人資料ID,全名,電話,電子郵件ID,城市,房屋ID,move_in_date,move_out日期,租金,最新的僱主,都生活在2015年1月至jan2016通過他們的租金排序的時間段一些特定城市住戶的降序排列 試過像這樣的occupationalcategory:

select pr.first_name+' '+pr.last_name as full_name, 
     pr.email, 
     pr.phone, 
     pr.profile_id, 
     th.house_id, 
     th.move_in_date, 
     th.move_out_date, 
     th.rent, 
     ed.latest_employer, 
     ed.Occupational_category, 
     ref.cnt 
    from Profiles pr, 
     Tenancy_histories th, 
     Employment_details ed 
     INNER JOIN (select [referrer_id(same as profile id)], 
        count([referrer_id(same as profile id)]) as cnt 
        from Referrals 
       group by [referrer_id(same as profile id)]) as ref 
     on pr.profile_id = ref.[referrer_id(same as profile id)] 
where pr.profile_id = th.profile_id 
    and th.profile_id = ed.profile_id 
    and pr.profile_id IN 
     (select profile_id 
      from Tenancy_histories 
     where move_in_date >= convert(date, 'Jan 2015') 
      and move_out_date <= convert(date, 'Jan 2016')) 

四處錯誤:

多部分標識符「pr.profile_id」不能是b ound。內部連接部分有問題。也許INNER JOIN是不檢索數據

+1

你爲什麼要混合隱式和顯式'join'語法?將隱式連接更改爲顯式,然後嘗試運行您的查詢。同時避免使用隱式連接語法。 – zarruq

回答

1

這是你想要的正確方法:

SELECT pr.first_name+' '+pr.last_name as full_name, 
     pr.email, 
     pr.phone, 
     pr.profile_id, 
     th.house_id, 
     th.move_in_date, 
     th.move_out_date, 
     th.rent, 
     ed.latest_employer, 
     ed.Occupational_category, 
     count(ref.profile_id) 
FROM Profiles pr 
INNER JOIN Tenancy_histories th ON (pr.profile_id = th.profile_id AND move_in_date >= convert(date, 'Jan 2015') AND move_out_date <= convert(date, 'Jan 2016')) 
INNER JOIN Employment_details ed ON (th.profile_id = ed.profile_id) 
LEFT JOIN Referrals as ref ON (pr.profile_id = ref.profile_id) 
GROUP BY pr.first_name+' '+pr.last_name, 
     pr.email, 
     pr.phone, 
     pr.profile_id, 
     th.house_id, 
     th.move_in_date, 
     th.move_out_date, 
     th.rent, 
     ed.latest_employer, 
     ed.Occupational_category 

注:請不要使用convert(date, 'Jan 2015')但像convert(date,'20150101',112),而不是因爲它可以在服務器上工作,並在另一個上產生錯誤...搜索「datetime implicit conversion」以獲取更多關於此的詳細信息。