加入MySQL时转置数据

时间:2018-07-04 17:30:40

标签: mysql sql transpose

我有以下两个表:

描述未来

+--------+--------------+------+-----+---------+----------------+
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| ID     | int(11)      | NO   | PRI | NULL    | auto_increment |
| DATE   | date         | YES  |     | NULL    |                |
| NAME   | varchar(10)  | YES  |     | NULL    |                |
| VALUE  | decimal(4,2) | YES  |     | NULL    |                |
+--------+--------------+------+-----+---------+----------------+

描述索引;

+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| ID    | int(11)      | NO   | PRI | NULL    | auto_increment |
| DATE  | date         | YES  |     | NULL    |                |
| VALUE | decimal(4,2) | YES  |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+

在表未来中,我有这样的数据:

2018-06-13 AUG 2018 20.10
2018-06-13 SEP 2018 21.10

2018-06-14 AUG 2018 20.25
2018-06-14 SEP 2018 21.35
...

(通常我会从NAME =“ AUG 2018”的期货中选择*到DATE来查看当天的AUG 2018数据)

在表索引中,我有像这样的简单数据:

2018-06-13 32.10
2018-06-14 32.50
...

现在,我想生成一个像这样的简单报告:

+------------+-------+----------+----------+
| DATE       | INDEX | AUG 2018 | SEP 2018 |
+------------+-------+----------+----------+
| 2018-06-13 | 32.10 | 20.10    | 21.10    |
| 2018-06-14 | 32.50 | 20.25    | 21.35    |
+------------+-------+----------+----------+

索引期货表必须在DATE之前合并在一起)

在MySQL中是否有可能?还是我必须使用脚本语言?

谢谢

1 个答案:

答案 0 :(得分:1)

一种方法使用join和聚合:

select i.date, i.index,
       max(case when f.name = 'Aug' then f.value end) as Aug,
       max(case when f.name = 'Sep' then f.value end) as Sep
from index i left join
     futures f
     on i.date = f.date
group by i.date, i.index;

这可以很好地扩展,但是需要汇总所有数据。另一种方法是使用两个联接:

select i.date, i.index,
       faug.value as aug, fsep.value as sep
from index i left join
     futures faug
     on faug.date = i.date and faug.name = 'Aug' left join
     futures fsep
     on fsep.date = i.date and fsep. name = 'Sep';

请注意,index是一个SQL关键字,因此它是表的坏名称。