Question

SET @qdate := '2014-02-17';
SELECT 
    com.trading_code,
    com.business_segment_id,
    dmkt.close_price,
    dmkt.cdate,
    dmkt.turnover,
    dmkt.volume,
    sh.total_no_share,
    IF(dmkt.close_price IS NULL,
        ((SELECT 
                close_price
            FROM
                daily_mkt_status
            WHERE
                trading_code = com.trading_code
                    AND cdate <= @qdate
            ORDER BY cdate DESC
            LIMIT 1) * sh.total_no_share),
        (dmkt.close_price * sh.total_no_share)) AS mcap
FROM
    company AS com
        LEFT JOIN
    daily_mkt_status AS dmkt ON (com.trading_code = dmkt.trading_code
        AND dmkt.cdate = @qdate )
        LEFT JOIN
    share_info AS sh ON (com.trading_code = sh.trading_code)

This code works only when i use the variable like

SET @qdate :- '2014-02-17' 

but what i want it to be is to be an array of dates from another table like this

SET @qdate IN (SELECT cdate FROM market_index);

the qdate will cycle through all the date from the table market_index. i have gone through all the array variable questions but non worked for me because of this part of my code

cdate <= @qdate

but i need this part to be there or my query doen't give me the output that i want.

hope i was clear, and many thanks in advance.

Was it helpful?

Solution

Why not simply join the market_index table?

SELECT
    com.trading_code,
    com.business_segment_id,
    dmkt.close_price,
    dmkt.cdate,
    dmkt.turnover,
    dmkt.volume,
    sh.total_no_share,
    mi.cdate
    IF(dmkt.close_price IS NULL,
        ((SELECT
                close_price
            FROM
                daily_mkt_status
            WHERE
                trading_code = com.trading_code
                    AND cdate <= mi.cdate
            ORDER BY cdate DESC
            LIMIT 1) * sh.total_no_share),
        (dmkt.close_price * sh.total_no_share)) AS mcap
FROM
    company AS com
    JOIN market_index AS mi
    LEFT JOIN daily_mkt_status AS dmkt ON (
        com.trading_code = dmkt.trading_code
        AND dmkt.cdate = mi.cdate
    )
    LEFT JOIN share_info AS sh ON (com.trading_code = sh.trading_code)

You might want to add a GROUP BY clause as well just to get rid of unnecessary duplicates

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top