我使用了以下stackoverflow帖子来尝试获取最新日期的记录: Select info from table where row has max date
我写了以下查询:
SELECT AR_SQ.SYMBOL, AR_SQ.NAME, AR_SQ.LAST, FF_PS.SECTOR, FF_PS.SECTOR_TAGS, HP.LAST_10_DAYS, HP.YTD_PERF
FROM AR_STOCK_QUOTE AR_SQ
LEFT JOIN (
SELECT HP.SYMBOL, max(TRADE_DATE) as MaxDate
FROM FF_HISTORICAL_STOCK_PRICE HP
GROUP BY HP.SYMBOL
)
HP on HP.SYMBOL = AR_SQ.SYMBOL
JOIN FF_PRIMARY_STOCK_TABLE FF_PS on FF_PS.SYMBOL = AR_SQ.SYMBOL
当我这样做时,我收到一条错误消息,说明如下:
错误代码:1054。“字段列表”中的未知列“HP.LAST_10_DAYS”
为什么会出现这种情况,因为定义了HP并且它是该表中的一个字段?
答案 0 :(得分:2)
因为你在select语句上进行连接而不是表" FF_HISTORICAL_STOCK_PRICE"您无法在全局选择中使用HP,因为HP未在此处定义
SELECT AR_SQ.SYMBOL, AR_SQ.NAME, AR_SQ.LAST, FF_PS.SECTOR, FF_PS.SECTOR_TAGS, HP.LAST_10_DAYS, HP.YTD_PERF #3- you cannot use HP here
FROM AR_STOCK_QUOTE AR_SQ
LEFT JOIN (
# 1- you are not doing ajoin on the table FF_HISTORICAL_STOCK_PRICE HP
# 2- you can use HP on this select
SELECT HP.SYMBOL, max(TRADE_DATE) as MaxDate
FROM FF_HISTORICAL_STOCK_PRICE HP
GROUP BY HP.SYMBOL
)
HP on HP.SYMBOL = AR_SQ.SYMBOL
JOIN FF_PRIMARY_STOCK_TABLE FF_PS on FF_PS.SYMBOL = AR_SQ.SYMBOLenter code here
将字段添加到连接部分中的select语句,现在它们将存在于结果HP上,并尝试为选择使用不同的别名
SELECT AR_SQ.SYMBOL, AR_SQ.NAME, AR_SQ.LAST, FF_PS.SECTOR, FF_PS.SECTOR_TAGS, RS.LAST_10_DAYS, RS.YTD_PERF
FROM AR_STOCK_QUOTE AR_SQ
LEFT JOIN (
# add the last_10_days to the fields of you select statement now you can select them
SELECT HP.SYMBOL, max(TRADE_DATE) as MaxDate ,HP.LAST_10_DAYS, HP.YTD_PERF
FROM FF_HISTORICAL_STOCK_PRICE HP
GROUP BY HP.SYMBOL
) RS on RS.SYMBOL = AR_SQ.SYMBOL #HP is a result of select statement
JOIN FF_PRIMARY_STOCK_TABLE FF_PS on FF_PS.SYMBOL = AR_SQ.SYMBOL