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 |
我遇到了輸出問題,它的工作原理 - 種類。我可以使用locationid嗎?對不起,我只是按照訂單 – hearmeroar
你是什麼意思locationid?你有8個不同的位置id你如何確定哪個id進入每一列? – Taryn
哦,是的。嗯.. – hearmeroar