参考这篇文章:https ://stackoverflow.com/questions/19985340/convert-rows-to-columns-in-mysql
我有这个代码,它连接了两个具有不同列名称的表,我想我可以这样做,以便我可以使用 bluefeet 的代码,因为我有单独的表,其中字符串位置在 table_1 上,位置 id 在 table_2 上。看起来像这样
表格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 |