[英]Row into Column in mysql without pivot and group concat
I have a table like 我有一张桌子
ID Student Exam
----------------------
1 Kavi BE
2 MGR BA
3 MGR1 BE
I am writing this data in excel format.The problem is that i need the exam field to be a column-wise like, 我正在以excel格式写入此数据。问题是我需要将检查字段设置为按列显示,
BE BA
-------------
Kavi NULL
NULL MGR
MGR1 NULL
This should be done only with the query,because i can't modify excel class to make it to print column-wise data. 这只能用查询完成,因为我无法修改excel类使其打印按列数据。
I have used group concat,but i need the exam details to be of a separate column and not in same column.I shouldnot use pivot since it is not supported by few versions of mysql. 我已经使用了group concat,但是我需要将考试详细信息放在单独的列中而不是在同一列中。我不应该使用数据透视表,因为少数版本的mysql不支持它。 Pls Help.
请帮助。
Note: This table may have as many as records,so pls provide solutions that can work dynamically. 注意:此表可能具有最多记录,因此请提供可以动态工作的解决方案。
MySQL doesn't have a PIVOT function so you will need to use an aggregate function with a CASE expression to get the result: MySQL没有PIVOT函数,因此您需要使用带有CASE表达式的聚合函数来获取结果:
select
max(case when exam = 'BE' then student end) BE,
max(case when exam = 'BA' then student end) BA
from yourtable
group by id;
See SQL Fiddle with Demo . 请参阅带有演示的SQL Fiddle 。
If you are going to have an unknown number of exam
values then you will need to look at using a prepared statement with dynamic sql. 如果您要获得未知数量的
exam
值,则需要使用动态SQL准备的语句。 The code will be similar to: 该代码将类似于:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when exam = ''',
exam,
''' then student end) AS `',
exam, '`'
)
) INTO @sql
from yourtable;
SET @sql
= CONCAT('SELECT ', @sql, '
from yourtable
group by id;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See SQL Fiddle with demo . 请参阅带有演示的SQL Fiddle 。 Both versions give the result:
这两个版本都给出结果:
| BE | BA |
| Kavi | (null) |
| (null) | MGR |
| MGR1 | (null) |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.