美文网首页
面试问题【mysql行转列,列转行】

面试问题【mysql行转列,列转行】

作者: 离家出走的小白 | 来源:发表于2022-02-25 16:04 被阅读0次

1、行转列

max/sum加上group by【注:在工作当中很少用到存储过程,更多的是用java等语言配合mysql解决实际问题,所以就不说存储过程的方式】

代码:

-- 行转列:主要是通过max/sum实现的,如果要动态可以借助java,写个for循环。循环传值【列:以时间位列,显示近15天的出库量】

-- 方法一

SELECT s_name,max(case when c_name='java' then score else 0 end) java,max(case when c_name='c#' then score  else 0 end) cc,

max(case when c_name='php' then score  else 0 end)  php

FROM user_score_info GROUP BY s_name;

SELECT s_name,sum(case when c_name='java' then score else 0 end) java,sum(case when c_name='c#' then score  else 0 end) cc,

sum(case when c_name='php' then score  else 0 end)  php

FROM user_score_info GROUP BY s_name;

-- 方法二

select distinct a.s_name ,IFNULL((select score from user_score_info b where b.s_name = a.s_name and c_name="java"),0) java,

IFNULL((select score from user_score_info b where b.s_name = a.s_name and c_name="c#"),0) cc,

IFNULL((select score from user_score_info b where b.s_name = a.s_name and c_name="php") ,0) php from user_score_info a;

2、列转行:【主要用到union】

sql脚本

-- 主要使用union实现的

select user_name ,"java" course,java_SCORE score from test_tb_grade2

UNION select user_name ,"c#" course,c_score score from test_tb_grade2

UNION select user_name ,"php" course,php_SCORE score from test_tb_grade2

order by user_name,course

select user_name ,"java" course,java_SCORE score from test_tb_grade2

UNION all select user_name ,"c#" course,c_score score from test_tb_grade2

UNION all select user_name ,"php" course,php_SCORE score from test_tb_grade2

order by user_name,course

相关文章

  • sql中列转行unpivot、行转列pivot详细讲解||Mys

    目录:一、sqlserver列转行、行转列详解二、Oracle列转行、行转列详解三、DB2列转行、行转列详解四、M...

  • 面试问题【mysql行转列,列转行】

    1、行转列 max/sum加上group by【注:在工作当中很少用到存储过程,更多的是用java等语言配合mys...

  • MySQL行转列,列转行

    参考: MySQL行转列实现和总结 mysql中列转行,并多个字段转到一行中的一个字段上,中间用逗号分开 mysq...

  • mysql行转列,列转行

    一、行转列 即将原本同一列下多行的不同内容作为多个字段,输出对应内容。 建表语句 插入数据 查询数据表中的内容(即...

  • mysql开发技巧笔记

    行转列 结果 使用 SUM 进行 行转列 列转行 应用场景 属性拆分 etl数据处理 1. 利用序列表处理列转行的...

  • sql行转列,列转行

    行转列,列转行是我们在开发过程中经常碰到的问题。行转列一般通过CASE WHEN 语句来实现,也可以通过 SQL ...

  • Hive的几个复杂情况

    行转列与列转行: https://blog.csdn.net/jx_870915876/article/detai...

  • SQL行列转换

    行转列1.1、case when1.2、内置函数pivot 列转行2.1、unpivot2.2、union实现

  • hive 行转列 列转行

    列转行 数据分析时需要行中的数据拆成多列,则需要用到:1,lateral view2,explode原始表tabl...

  • SQL列转行、行转列

    笔者前不久终于发布了自己的APP《小印记》,希望读者能前往App Store下载《小印记》支持一下笔者,谢谢!? ...

网友评论

      本文标题:面试问题【mysql行转列,列转行】

      本文链接:https://www.haomeiwen.com/subject/mugxrrtx.html