【问题标题】:Sub-queries, joins in one query子查询,加入一个查询
【发布时间】:2018-03-12 03:12:33
【问题描述】:

我有五张桌子。我需要从他们所有人那里获取数据。表 'Tenancy_histories' 包含 move_in_date、move_out_date、rent 列。 'Profiles' 包含 first_name、last_name、email、profile_id 等。'Referrals' 包含referrer_bonus_amount 和类似的其他数据。最重要的是,它包含由特定 profile_id 进行的推荐次数,这是该 profile_id 在“referrer_id(与配置文件 ID 相同)”列中出现的次数。 'Employment_details' 包含最新的雇主,职业类别

我需要写一个查询来显示个人资料 id、全名、电话、电子邮件 id、城市、房子 id、move_in_date、move_out 日期、租金、推荐总数、最新雇主和所有居住租户的职业类别在 2015 年 1 月至 2016 年 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,  
       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”。内部连接部分有问题。也许 INNER JOIN 不是检索数据的正确方法

【问题讨论】:

  • 你为什么混合implicitexplicitjoin语法?将隐式连接更改为显式连接,然后尝试运行您的查询。还要避免使用隐式连接语法。

标签: sql sql-server sql-server-2005 subquery inner-join


【解决方案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) 之类的东西,因为它可以在服务器上运行,并在另一个服务器上引发错误...搜索“日期时间隐式转换”以获取更多详细信息.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    相关资源
    最近更新 更多