Mysql实现行列转换

Mysql实现行列转换,第1张

mysql数据库如何实现行列转换


方案一:

select  name,
sum(case when course='java' then grade end) as java,
sum(case when course='C++' then grade end) as C++,
sum(case when course='C#' then grade end) as C#
from test group by name

方案二:

select distinct c.`name` AS name,
(select grade from test where name = c.`name` and course = 'java' )as java,
(select grade from test where name = c.`name` and course = 'C++' )as C++,
(select grade from test where name = c.`name` and course = 'C#' )as C#
from test c

结合项目用到的sql:

select  MAIN_STATION_CODE_ as stationCode,
case when SUBSTR(PLAN_START_DATE_, 1, 10)=curdate() then STATION_ else "" end as firstDay,
case when SUBSTR(PLAN_START_DATE_, 1, 10)=DATE_SUB(curdate(),INTERVAL -1 DAY) then STATION_ else "" end as secondDay,
case when SUBSTR(PLAN_START_DATE_, 1, 10)=DATE_SUB(curdate(),INTERVAL -2 DAY) then STATION_ else "" end as thirdDay,
case when SUBSTR(PLAN_START_DATE_, 1, 10)=DATE_SUB(curdate(),INTERVAL -3 DAY) then STATION_ else "" end as fourthDay
from ps_overhaul_plan_row group by MAIN_STATION_CODE_

方案三:带汇总
select ifnull(uid,'Total') uid, uname,
sum(if(`course`='java',grade,0)) 'java',
sum(if(`course`='C++',grade,0)) 'C++',
sum(if(`course`='C#',grade,0)) 'C#',
sum(score) 'total'
from course
group by uid
with ROLLUP

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/991937.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存