从两个MySQL表中选择和分组

时间:2014-03-17 21:44:28

标签: mysql sql pivot union

我有两个表...一个包含股票市场各种指数的每日价值,即FTSE100,纳斯达克等。列和一些样本数据:

id, index_name, date,      value
1,  FTSE100,    03/03/01,  8998.90 

另一张表包含个别股票的股票价格。列是:

id, stock_name, date,       value
1,  fb,         02/03/01,   45
2,  twtr,       01/01/01,   398.00
3,  twtr,       02/03/01,   399.50

我需要(理想情况下只在SQL中)查询股票和指数的任意组合,例如fb,twtr,ftse100并显示以下输出:

 Date,      fb,     twtr,     ftse100
 01/01/01,  null,   398.00,   null
 02/03/01,  45,     399.50,   null
 03/03/01,  null,   null,     8998.90

任何人都可以帮助合理有效地完成这项工作吗?谢谢。

1 个答案:

答案 0 :(得分:1)

这可能对您的需求有用:

SELECT date,
       MAX(CASE WHEN name='fb' THEN value ELSE NULL END) AS fb,
       MAX(CASE WHEN name='twtr' THEN value ELSE NULL END) AS twtr,
       MAX(CASE WHEN name='FTSE100' THEN value ELSE NULL END) AS ftse100
  FROM (SELECT date, index_name AS name, value FROM index_table
        UNION
        SELECT date, stock_name AS name, value FROM stock_table)
        AS derivedtable
 GROUP BY date