将行转换为mySql中的列

时间:2014-12-13 17:30:08

标签: mysql

我有一张桌子,看起来像这样

RegNo------------Subject-----------------Eligibility
112109-----------CMIS 1113---------------Eligible
112109-----------ELTN 1113---------------Not Eligible
112109-----------IMGT 1113---------------Eligible
112108-----------CMIS 1113---------------Eligible
112108-----------ELTN 1113---------------Not Eligible
112108-----------IMGT 1113---------------Not Eligible
112107-----------CMIS 1113---------------Eligible

我想按照以下方式转换上表

RegNo------------CMIS 1113-----------------ELTN 1113--------------IMGT 1113
112109-----------Eligible------------------Not Eligible-----------Eligible
112108-----------Eligible------------------Not Eligible-----------Not Eligible
112107-----------Eligible------------------Null-------------------Null

我不知道这是否可能。所以如果有人能帮助我,我将非常感激。谢谢你

2 个答案:

答案 0 :(得分:2)

对于行中需要显示为列的一组已知值,可以使用以下技术完成。

SELECT
  RegNo,
  max(if(Subject = 'CMIS 1113', Eligibility, NULL)) as `CMIS 1113`,
  max(if(Subject = 'ELTN 1113', Eligibility, NULL)) as `ELTN 1113`,
  max(if(Subject = 'IMGT 1113', Eligibility, NULL)) as `IMGT 1113`
from table_name 
group by RegNo

答案 1 :(得分:1)

您无法通过可变列数获取数据结果 但是,如果预定义了一组主题值,则可能... 您可以像这样构建查询:

$subjects = array(
  'CMIS 1113',
  'ELTN 1113',
  'IMGT 1113'
);

$joins = array();
$fields = array();
for ($i=0; $i<count($subjects); $i++) {
  $joins[] = "LEFT JOIN Table t{$i} ON t0.ReqNo=t{$i}.ReqNo AND Subject = '{$subjects[$i]}'";
  $fields[] = "t{$i}.Eligibility as `{$subjects[$i]}`";
}
$joins = implode(' ', $joins);
$fields = implode(',', $fields);

$sql = "SELECT t.ReqNo, $fields
From table t
$joins
Group by t.ReqNo
";

结果查询将如下:

SELECT t.ReqNo, t0.Eligibility as `CMIS 1113` /*similar fields*/
From table t
LEFT JOIN table t0 ON t.ReqNo = t0.ReqNo AND t0.Subject = 'CMIS 1113'
/*similar joins*/
Group by t.ReqNo