2013-11-14 55 views
0

在参考这个帖子:https://stackoverflow.com/questions/19985340/convert-rows-to-columns-in-mysql转换行到列在MySQL V2

我有这样的代码在那里种加入与DIFF科拉姆名称连接两个表,我想我能做到这一点,这样我可以使用bluefeet的代码,因为我有单独的表,其中字符串位置在table_1上,位置ID在table_2上。它看起来像这样

TABLE_1:

id | location 
1 | East Flow 
2 | East Level 
3 | East Pressure 
4 | East MR 
5 | West Flow 
6 | West Level 
7 | West Pressure 
8 | West MR 

表2:

locationid | val 
    1  | 10 
    2  | 20 
    3  | 30 
    4  | 40 
    5  | 100 
    6  | 200 
    7  | 300 
    8  | 400 

所以,当你执行这个查询会是这个样子:

SELECT id, locationid, location, val 
FROM table_1, table_2 
WHERE id = locationid 
GROUP BY id 

输出:

id | locationid |  location | val 
1 |  1  | East Flow  | 10 
2 |  2  | East Level | 20 
3 |  3  | East Pressure | 30 
4 |  4  | East MR  | 40 
5 |  5  | West Flow  | 100 
6 |  6  | West Level | 200 
7 |  7  | West Pressure | 300 
8 |  8  | West MR  | 400 

我想合并@ bluefeet的代码,我的代码,这样我可以用她的代码,导致她的代码已经工作:

select 
    substring_index(location, ' ', 1) Location, 
    max(case when location like '%Flow' then val end) Flow, 
    max(case when location like '%Level' then val end) Level, 
    max(case when location like '%Pressure' then val end) Pressure, 
    max(case when location like '%MR' then val end) MR 
from yourtable 
group by substring_index(location, ' ', 1) 

如何合并呢?选择一个选择或东西? 这是我是如何希望输出会是什么样子:

从这:

Location | Val | 
East Flow  | 10 | 
East Level | 20 | 
East Pressure | 30 | 
East MR  | 40 | 
West Flow  | 100 | 
West Level | 200 | 
West Pressure | 300 | 
West MR  | 400 | 

要这样:

Location | Flow| Level | Pressure | MR | 
East  | 10 | 20 | 300 | 400 | 
West  | 100 | 200 | 300 | 400 | 

回答

2

你应该能够刚刚加入你的表得到的结果:

select 
    substring_index(t1.location, ' ', 1) Location, 
    max(case when t1.location like '%Flow' then t2.val end) Flow, 
    max(case when t1.location like '%Level' then t2.val end) Level, 
    max(case when t1.location like '%Pressure' then t2.val end) Pressure, 
    max(case when t1.location like '%MR' then t2.val end) MR 
from table_1 t1 
inner join table_2 t2 
    on t1.id = t2.locationid 
group by substring_index(t1.location, ' ', 1) 

SQL Fiddle with Demo

+0

我遇到了输出问题,它的工作原理 - 种类。我可以使用locationid吗?对不起,我只是按照订单 – hearmeroar

+0

你是什么意思locationid?你有8个不同的位置id你如何确定哪个id进入每一列? – Taryn

+0

哦,是的。嗯.. – hearmeroar