如何连接三个具有一个公共列的选择查询

时间:2014-09-15 17:47:11

标签: sql join

我有三个选择查询,如下所示,提供相应的输出

select DATE_FORMAT(table1.value_date,'%b')as Month,
       DATE_FORMAT(table1.value_date,'%Y') as Year,
       table1.open as Open 
from index_main as table1 
    join ( select min(`value_date`) `value_date` 
           from index_main 
           group by month(`value_date`), year( `value_date`) 
    ) as table2 on table1.`value_date` = table2.`value_date`

输出列 - 月,年,开放

select DATE_FORMAT(table1.value_date,'%b')as Month,
    DATE_FORMAT(table1.value_date,'%Y') as Year,
    table1.close as Open 
from index_main as table1 
    join ( select max(`value_date`) `value_date` 
           from index_main group by month(`value_date`), year( `value_date`) 
    ) as table2 on(table1.`value_date` = table2.`value_date`)

输出列 - 月,年,关闭

select DATE_FORMAT(table1.value_date,'%b')as Month,
    DATE_FORMAT(table1.value_date,'%Y') as Year,
    max(table1.high) as High 
FROM `index_main` as table1 
GROUP BY table1.month,table1.year 
ORDER BY year(table1.value_date) desc, month(table1.value_date) desc

输出列 - 月,年,高,低

我想根据常用列加入这三个选择查询,即月份和时间。年。

我的最终结果应该包含以下列:月,年,开,关,高,低。

1 个答案:

答案 0 :(得分:0)

试试这个。

首先创建3个视图,每个视图一个(vw1,vw2和vw3)。然后使用如下查询:

SELECT vw1.Month, vw1.Year, Open, Close High FROM vw1 LEFT join vw2 on vw1.Year=vw2.Year and vw1.Month=vw2.Month LEFT JOIN vw3 on vw1.Year=vw3.Year and vw1.Month=vw3.Month

希望这会对你有所帮助。