使用子查询选择获取列值

时间:2018-11-15 16:24:36

标签: mysql sql

我有以下查询:

SELECT 
p.fsym_id, 
b.p_co_sec_name_desc AS Company_Name,
p.p_date,
p.p_price AS Unadjusted_Price,
b.region AS Region,
f_splitadjprice(p.fsym_id,p.p_date,p.p_price) AS O_Split_Adjusted_Price,
f_prevunadjprice(p.fsym_id,p.p_date,Previous_Date,p.p_price),
(
SELECT MAX(f.p_date)
FROM fp_v2_fp_basic_prices AS f 
WHERE f.fsym_id = p.fsym_id AND f.p_date<p.p_date
)  Previous_Date

FROM
fp_v2_fp_basic_prices p

LEFT JOIN (
        SELECT r2.region, b2.p_co_sec_name_desc, b2.fsym_id
        FROM  fp_v2_fp_sec_coverage b2
        LEFT JOIN sym_v1_sym_region r2 ON b2.fsym_id = r2.fsym_id
        WHERE r2.region = "EUR") b
        ON b.fsym_id =p.fsym_id;

当尝试调用函数f_prevundadjprice时,出现错误“ Previous_date不在列列表中”。基本上我想做的是使用(SELECT MAX ..)创建列的上一个日期,然后在函数f_prevunadjprice中使用此列中的值。

2 个答案:

答案 0 :(得分:0)

您已经有一个子查询。如果您使用的是TSQL,则可以外部应用第二个。 MySQL不支持套用,所以您必须加入它:

SELECT 
p.fsym_id, 
b.p_co_sec_name_desc AS Company_Name,
p.p_date,
p.p_price AS Unadjusted_Price,
b.region AS Region,
f_splitadjprice(p.fsym_id,p.p_date,p.p_price) AS O_Split_Adjusted_Price,
f_prevunadjprice(p.fsym_id,p.p_date,Previous_Date,p.p_price),
PreviousDate.maxdate

FROM
fp_v2_fp_basic_prices p

LEFT JOIN (
        SELECT r2.region, b2.p_co_sec_name_desc, b2.fsym_id
        FROM  fp_v2_fp_sec_coverage b2
        LEFT JOIN sym_v1_sym_region r2 ON b2.fsym_id = r2.fsym_id
        WHERE r2.region = "EUR") b

        ON b.fsym_id =p.fsym_id;

LEFT JOIN (

SELECT f.fsym_id,f.p_date,MAX(f.p_date) as maxdate
FROM fp_v2_fp_basic_prices AS f 
group by f.fsym_id, f.p_date
)  Previous_Date

on  Previous_Date.fsym_id = p.fsym_id and AND Previous_Date.p_date<p.p_date

答案 1 :(得分:0)

如果您使用 p。来引用来自fp_v2_fp_basic_prices的所有字段,则还应该在下一行进行操作:

f_prevunadjprice(p.fsym_id,p.p_date,Previous_Date,p.p_price)

尝试通过以下方式更改它:

f_prevunadjprice(p.fsym_id,p.p_date,p.Previous_Date,p.p_price)

如果继续出现相同的错误,则应确保表/视图 fp_v2_fp_basic_prices 包含名为 Previous_Date

的列

您还应该在此处使用AS:

(
SELECT MAX(f.p_date)
FROM fp_v2_fp_basic_prices AS f 
WHERE f.fsym_id = p.fsym_id AND f.p_date<p.p_date
)  Previous_Date

所以:

...) AS Previous_Date