mysql 指定列转成行

由于项目需要将列得内容当做字段名

将同一家公司名称不同的状态(每个状态一条数据) 合成一条数据,且将状态的对应时间作为字段名


 select B.seId,B.company, B.short,  
 max(if(A.stat=101, A.statDate,NULL )) as qStatDate,
 max(if (A.stat=102,A.statDate,NULL )) as wStatDate,
 max(if(A.stat=103, A.statDate,NULL )) as zStatDate,
 max(if(A.stat=201, A.statDate,NULL )) as yStatDate,
 max(if(A.stat=201, A.ref,NULL )) as yRef,
 max(if(A.stat=202, A.statDate,NULL )) as yStatDate,
 max(if(A.stat=202, A.ref,NULL )) as yRef,
 max(if(A.stat=203, A.statDate,NULL )) as yStatDate,
 max(if(A.stat=204, A.statDate,NULL )) as yStatDate,
 max(if(A.stat=204, A.ref,NULL )) as yRef,
 max(if(A.stat=205, A.statDate,NULL )) as gStatDate,
 max(if(A.stat=205, A.ref, NULL )) as gRef,
 max(if(A.stat=206, A.statDate,NULL )) as zStatDate,
 max(if(A.stat in (207,208), A.statDate,NULL )) as zhStatDate,
 max(if(A.stat=209, A.statDate,NULL )) as fStatDate,
 max(if(A.stat=210, A.statDate,NULL )) as fsStatDate,
 max(if(A.stat=211, A.statDate,NULL )) as zhbStatDate,
 max(if(A.stat=212, A.statDate,NULL )) as ssStatDate,
 max(if(A.stat=212, A.ref,NULL )) as ssRef,
 max(if(A.stat=213, A.statDate,NULL )) as sswStatDate,
 max(if(A.stat=213, A.ref,NULL )) as sswRef,
 max(if(A.stat=214, A.statDate,NULL )) as zhsStatDate,
 max(if(A.stat=214, A.ref,NULL )) as zhsRef,
 max(if(A.stat=215, A.statDate,NULL )) as fsStatDate,
 max(if(A.stat=216, A.statDate,NULL )) as fswStatDate
from (SELECT seId, stat, statDate, ref FROM dws_detail where dataStatus<>3) as A LEFT JOIN (SELECT seId,company, short FROM dws_base where dataStatus<>3) AS B ON A.seId=B.seId  GROUP BY A.seId

有个地方要注意

通过查资料显示可以使用

"""case ZZZ  when XXX  then YYY else AAA end""" 使用 case when 这种方式取值 如果 A.stat 对应 A.statDate 属于一一对应,则使用这种方式,只能保证值会取到,但是不会一一对应,也就是如果A.stat = 101 对应A.statDate 是2020-01-01 那么就会出现对应出错。

101 对应qdStatDate 字段;103 对应 zzssStatDate 字段 ,因此使用case when 方式进行列转行,针对列得内容较多且会映射不同内容的情况下效果不明显

""" if (XXX, YYY, ZZZZ)"""" 使用这种方式取值可以解决上述提到的问题

"""max(if(XXX, YYY, ZZZZ))"" 使用这种方式可以解决出现取到多个值时,选择最大值

个人在项目中遇到的问题,仅供参考

猜你喜欢

转载自blog.csdn.net/weixin_43124425/article/details/112980254