使用新别名列作为键连接表

时间:2015-10-28 18:03:09

标签: sql sql-server mysql-workbench amazon-redshift

当我尝试将2个表与我的数据连接时,我收到一个错误,我的引用不明确,或者我得到的原始表没有别名列。

这是我第一个使用sql的项目,也是我的一个重要学习点,所以我很欣赏这个指导。

这是我的代码。

WITH 
RentDotComOnly AS
(
  SELECT 
    concat(DATE_PART(mm,archived_apartments.week),clean_zip) AS "monthlyzip",
    COUNT(clean_zip) AS "rent_count_clean_zip", 
    AVG((low_price+high_price)/2) AS "rent_avg_price", 0.85*min(low_price) AS "rent_lower_bound", 1.15*max(high_price) AS "rent_upper_bound"
  FROM 
    archived_apartments 
  WHERE 
    source_type in (29,36,316) 
    AND week between '2015-07-06' and '2015-10-12' 
    AND is_house <> 1  
    AND archived_apartments.high_price <> 0 
  GROUP BY monthlyzip
),
AllRJData AS
(
  SELECT
    concat(DATEPART(mm,archived_apartments.week),clean_zip) AS "monthlyzip",
    COUNT(clean_zip) AS "all_count_clean_zip", 
    AVG((low_price+high_price)/2) AS "all_avg_price"
  FROM 
    archived_apartments 
  WHERE 
    week between '2015-07-06' and '2015-10-12' 
    AND is_house <> 1  
  GROUP BY monthlyzip
)
SELECT 
  concat(DATE_PART(mm,archived_apartments.week),clean_zip) AS "monthlyzip",
  COUNT(archived_apartments.clean_zip) as filtered_count_clean_zip, 
  RentDotComOnly.rent_count_clean_zip, RentDotComOnly.rent_avg_price, RentDotComOnly.rent_lower_bound, RentDotComOnly.rent_upper_bound,
  AllRjData.all_count_clean_zip, AllRjData.all_avg_price
FROM
archived_apartments 
JOIN AllRJData 
ON concat(DATE_PART(mm,archived_apartments.week),archived_apartments.clean_zip) = AllRJData.monthlyzip
JOIN RentDotComOnly
ON concat(DATE_PART(mm,archived_apartments.week),archived_apartments.clean_zip) = RentDotComOnly.monthlyzip
WHERE 
  archived_apartments.week between '2015-07-06' and '2015-10-12'
  AND archived_apartments.is_house <> 1 
  AND archived_apartments.high_price <> 0 
  AND archived_apartments.low_price > RentDotComOnly.rent_lower_bound
  OR archived_apartments.high_price < RentDotComOnly.rent_upper_bound
  AND archived_apartments.week between '2015-07-06' and '2015-10-12'
  AND archived_apartments.is_house <> 1 
  AND archived_apartments.high_price <> 0 
GROUP BY monthlyzip
RentDotComOnly.rent_count_clean_zip, RentDotComOnly.rent_avg_price, RentDotComOnly.rent_lower_bound, RentDotComOnly.rent_upper_bound, 
AllRjData.all_count_clean_zip, AllRjData.all_avg_price
ORDER BY monthlyzip

1 个答案:

答案 0 :(得分:0)

问题是您在联接中引用的monthlyzip列不明确。你有三个表与那个列,你指的是哪个表?

如果archived_apartments上存在monthly_zip,您可以执行以下操作:

FROM
archived_apartments JOIN
AllRJData 
ON archived_apartments.monthlyzip = AllRJData.monthlyzip
JOIN RentDotComOnly 
ON archived_apartments.monthlyzip = RentDotComOnly.monthlyzip

但听起来monthly_ziparchived_apartments不存在,因此您无法真正加入该字段。相反,您必须加入用于制作monthlyzip的公式:

FROM
archived_apartments JOIN
AllRJData 
ON concat(DATEPART(mm,archived_apartments.week),archived_apartment.clean_zip)  = AllRJData.monthlyzip
JOIN RentDotComOnly 
ON concat(DATEPART(mm,archived_apartments.week),archived_apartment.clean_zip)  = RentDotComOnly.monthlyzip