MySql 将行转为列,将列转为行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19019453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySql Transpose Row into Column and Column into Row
提问by danielelisondaya
i have problem with transposing row to column and column to row. I can do that if it just transpose row to column or column to row.
我在将行到列和列到行转置时遇到问题。如果它只是将行到列或列到行转置,我可以做到这一点。
This my table with data
这是我的数据表
UNIT|JAN|FEB|MAR|APR|MEI|JUN
CS-1|100|200|300|400|500|600
CS-2|111|222|333|444|555|666
CS-3|331|123|423|923|918|123
and I would like to get the following output
我想得到以下输出
MONTH|CS-1|CS-2|CS-3
JAN |100 |111 |331
FEB |200 |222 |123
MAR |300 |333 |423
etc..
等等..
Anybody know how to do this? Thanks very much!
有人知道怎么做吗?非常感谢!
采纳答案by peterm
You can do it this way
你可以这样做
SELECT month,
MAX(CASE WHEN unit = 'CS-1' THEN value END) `CS-1`,
MAX(CASE WHEN unit = 'CS-2' THEN value END) `CS-2`,
MAX(CASE WHEN unit = 'CS-3' THEN value END) `CS-3`
FROM
(
SELECT unit, month,
CASE month
WHEN 'JAN' THEN jan
WHEN 'FEB' THEN feb
WHEN 'MAR' THEN mar
WHEN 'APR' THEN apr
WHEN 'MAY' THEN may
WHEN 'JUN' THEN jun
END value
FROM table1 t CROSS JOIN
(
SELECT 'JAN' month UNION ALL
SELECT 'FEB' UNION ALL
SELECT 'MAR' UNION ALL
SELECT 'APR' UNION ALL
SELECT 'MAY' UNION ALL
SELECT 'JUN'
) c
) q
GROUP BY month
ORDER BY FIELD(month, 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN')
Output:
输出:
| MONTH | CS-1 | CS-2 | CS-3 | |-------|------|------|------| | JAN | 100 | 111 | 331 | | FEB | 200 | 222 | 123 | | MAR | 300 | 333 | 423 | | APR | 400 | 444 | 923 | | MAY | 500 | 555 | 918 | | JUN | 600 | 666 | 123 |
Here is SQLFiddledemo
这是SQLFiddle演示