在mysql V2中将行转换为列
关于这一职位: 我有一段代码,它将两个不同列名称的表连接起来,我想我可以这样做,这样我就可以使用BlueFoots的代码,因为我有单独的表,其中字符串位置在表1上,位置id在表2上。看起来像这样 表1:在mysql V2中将行转换为列,mysql,sql,row,Mysql,Sql,Row,关于这一职位: 我有一段代码,它将两个不同列名称的表连接起来,我想我可以这样做,这样我就可以使用BlueFoots的代码,因为我有单独的表,其中字符串位置在表1上,位置id在表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: loc
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
我想将@BlueFoots的代码合并到我的代码中,这样我就可以使用她的代码,因为她的代码已经可以工作了:
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 |
您应该能够直接联接表以获得结果:
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)
请参见我的输出有问题,它可以正常工作-有点。我可以改用locationid吗?对不起,我只是在按订单做你说的locationid是什么意思?你有8个不同的位置id你如何确定哪个id进入每一列?你要提前知道位置id吗?@hearmeroar这将是一个可怕的方法来做这件事-但是试试这个演示-如果我们忘记了表1,只是在表2上使用位置id怎么办?