MySQL组行在一行中具有相同的ID

时间:2016-03-29 07:02:15

标签: mysql pivot

我尝试在MySQL中做一个像枢轴一样的东西,但我被卡住了。

我有一张看起来像这样的表:

original Table

我从以下查询开始:

    SELECT distinct
  p.id, p.uuid, p.kpiDate, p.kpiTime,
  CASE 
     WHEN p.subSysName = 'CMONE' THEN p.status 
     ELSE '' 
  END AS CMONE,
  CASE 
     WHEN p.subSysName = 'DISODAY' THEN p.status 
     ELSE '' 
  END AS DISODAY,
  CASE 
     WHEN p.subSysName = 'DIIN_HFFF' THEN p.status 
     ELSE '' 
  END AS DIIN_HFFF,
  CASE 
     WHEN p.subSysName = 'DIIN_PAL' THEN p.status 
     ELSE '' 
  END AS DIIN_PAL,
  CASE 
     WHEN p.subSysName = 'DISO_FAL' THEN p.status 
     ELSE '' 
  END AS DISO_FAL,
  CASE 
     WHEN p.subSysName = 'MBATCH' THEN p.status 
     ELSE '' 
  END AS MBATCH,
  CASE 
     WHEN p.subSysName = 'MO_BATCH' THEN p.status 
     ELSE '' 
  END AS MO_BATCH,
  CASE 
     WHEN p.subSysName = 'QINTER' THEN p.status 
     ELSE '' 
  END AS QINTER,
  CASE 
     WHEN p.subSysName = 'ZFIREWALL' THEN p.status 
     ELSE '' 
  END AS ZFIREWALL

FROM subsys_stat p
order by p.kpiDate, p.kpiTime

此查询的结果如下所示:

first query

所以我设法将每个subSysName作为列。

下一步应该是,具有相同UUID的每个条目也在同一行中,如下所示:

result table

我该怎么做? 我以为我可以通过连接来做到这一点(JOIN subsys_stat b ON ap.uuid = b.uuid)但这不起作用。

1 个答案:

答案 0 :(得分:3)

您需要为查询添加分组:

 SELECT MIN(p.id), p.uuid, p.kpiDate, p.kpiTime,
        MAX(CASE WHEN p.subSysName = 'CMONE' THEN p.status END) AS CMONE,
        MAX(CASE WHEN p.subSysName = 'DISODAY' THEN p.status END) AS DISODAY,
  ... etc
FROM subsys_stat p
GROUP BY p.uuid, p.kpiDate, p.kpiTime
ORDER BY p.kpiDate, p.kpiTime

此外,CASE表达式应该在MAX等聚合函数中使用。