Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

sql - mySQL create columns from rows

From this sort of table:

| id | in | value | valueMax |
| 1  | 1  |  10   |  25      |
| 1  | 2  |  11   |  25      |
| 1  | 3  |  12   |  25      |
| 2  | 1  |  20   |  35      |
| 2  | 2  |  21   |  35      |
| 2  | 3  |  22   |  35      |

Is it posible to make a select that returns this:

| id | value1 | valueMax1  | value2 | valueMax2  | value3 | valueMax3  |
| 1  |  10    |  25        |  11    |  25        |  12    |  25        |
| 2  |  20    |  35        |  21    |  35        |  22    |  35        |

So far i've tryed solutions with GROUP_CONCAT, or SELECT inside SELECT, but it's not the result i'm looking for. As per comment i'll show next what i want to happen if an IN = 4 is added.

With new data:

| id | in | value | valueMax |
| 1  | 1  |  10   |  25      |
| 1  | 2  |  11   |  25      |
| 1  | 3  |  12   |  25      |
| 1  | 4  |  13   |  35      |
| 2  | 1  |  20   |  35      |
| 2  | 2  |  21   |  35      |
| 2  | 3  |  22   |  35      |
| 2  | 4  |  23   |  35      |

Result of select:

| id | value1 | valueMax1  | value2 | valueMax2  | value3 | valueMax3  | value4 | valueMax4  |
| 1  |  10    |  25        |  11    |  25        |  12    |  25        |  13    |  35        |
| 2  |  20    |  35        |  21    |  35        |  22    |  35        |  23    |  35        |

NOTE: as an aditional feature, is there anyway to actually get a result like this WITHOUT knowing the exact number of IN values? so, the same query would work on a table with 2 posible values of IN, as well as on a table with 5 posible values.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this:

| id |  value    | valueMax   | 
| 1  |  10,11    |  25,25,25  | 
| 2  |  20,21    |  35,35,35  |

in this way:

SELECT id, GROUP_CONCAT(string SEPARATOR ' ') FROM table GROUP BY id;

How to use GROUP BY to concatenate strings in MySQL?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...