简体   繁体   中英

Using Subquery select to get column value

I have the following query:

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;

I get the error, "Previous_date not on column list" when trying to call the function f_prevundadjprice. Basically what I want to do is create the column previous date using (SELECT MAX..) and then use the value from this column in the function f_prevunadjprice.

you already have one subquery. If you were using TSQL you could outer apply the second one. MySQL doesn't support apply, so you'll have to left join to it:

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

If you use p. to reference all the fields coming from fp_v2_fp_basic_prices , you should also do it in the next line:

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

try to change it by:

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

If you continue with the same error, you should ensure the table/view fp_v2_fp_basic_prices has a column named Previous_Date

You should also use AS here:

(
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

So:

...) AS Previous_Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM