SQL行转列、列转行

SQL行转列、列转行这个主题还是比较常见的,行转列主要适用于对数据作聚合统计,如统计某类目的商品在某个时间区间的销售情况。列转行问题同样也很常见。一、整理测试数据createtablewyc_test( idint(32)notnullauto_increment, namevarchar(80)defaultnull, datedatedefaultn…

大家好,又见面了,我是你们的朋友全栈君。

SQL行转列、列转行

这个主题还是比较常见的,行转列主要适用于对数据作聚合统计,如统计某类目的商品在某个时间区间的销售情况。列转行问题同样也很常见。

一、整理测试数据

create table wyc_test(
	id int(32) not null auto_increment,
	name varchar(80) default null,
	date date default null,
	scount int(32),
	primary key (id)
);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (1,'小说','2013-09-01',10000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (2,'微信','2013-09-01',20000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (3,'小说','2013-09-02',30000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (4,'微信','2013-09-02',35000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (5,'小说','2013-09-03',31000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (6,'微信','2013-09-03',36000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (7,'小说','2013-09-04',35000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (8,'微信','2013-09-04',38000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (9,'小说','2013-09-01',80000);
INSERT INTO `wyc_test` (`id`,`name`,`date`,`scount`) VALUES (10,'微信','2013-09-01',70000);

二、行转列

主要思路是分组后使用case进行条件判断处理

#行转列
select 
    a.date,
    sum(case a.name
        when '小说' then a.scount
        else 0
    end) 'sum_小说',
    max(case a.name
        when '小说' then a.scount
        else 0
    end) 'max_小说',
    sum(case a.name
        when '微信' then a.scount
        else 0
    end) '微信',
    max(case a.name
        when '小说' then a.scount
        else 0
    end) 'max_微信'
from
    wyc_test a
group by date;

结果:

SQL行转列、列转行

三、列转行

主要思路也是分组后使用case

#列转行
select 
    a.date,
    concat('小说:',
            cast(sum(case a.name
                    when '小说' then a.scount
                    else 0
                end)
                as char),
            '微信',
            cast(sum(case a.name
                    when '微信' then a.scount
                    else 0
                end)
                as char)) as 'str'
from
    wyc_test a
group by a.date;
#列转行
#1.使用mysql提供的函数分组
select a.date,group_concat(a.name,'总量:', a.scount) from wyc_test a group by a.date,a.name;
#2.使用mysql提供的函数分组
select a.date,a.name, group_concat(a.name, '总量:', a.scount) from wyc_test a group by a.date,a.name;
#3.普通group结合字符串拼接
SELECT 
    a.date,
    concat('小说总量:',
            cast(sum(case a.name
                    when '小说' then a.scount
                    else 0
                end)
                as char)) as '小说',
    concat('微信总量:',
            cast(sum(case a.name
                    when '微信' then a.scount
                    else 0
                end)
                as char)) as '微信'
from
    wyc_test a
group by a.date;

结果:
SQL行转列、列转行

四、列转行详解
 
1.1、初始测试数据
        表结构:TEST_TB_GRADE2
Sql代码 
create table TEST_TB_GRADE2 

  ID         NUMBER(10) not null, 
  USER_NAME  VARCHAR2(20 CHAR), 
  CN_SCORE   FLOAT, 
  MATH_SCORE FLOAT, 
  EN_SCORE   FLOAT 

 
        初始数据如下图:

     SQL行转列、列转行  
 
1.2、 如果需要实现如下的查询效果图:

  SQL行转列、列转行                    
 
这就是最常见的列转行,主要原理是利用SQL里面的union,具体的sql语句如下:
Sql代码 
select user_name, ‘语文’ COURSE , CN_SCORE as SCORE from test_tb_grade2  
union select user_name, ‘数学’ COURSE, MATH_SCORE as SCORE from test_tb_grade2  
union select user_name, ‘英语’ COURSE, EN_SCORE as SCORE from test_tb_grade2  
order by user_name,COURSE  
 
 也可以利用【 insert all into … select 】来实现,首先需要先建一个表TEST_TB_GRADE3:
Sql代码 
create table TEST_TB_GRADE3   
    (  
      USER_NAME VARCHAR2(20 CHAR),   
      COURSE    VARCHAR2(20 CHAR),   
      SCORE     FLOAT   
    )   
 再执行下面的sql:
 
Sql代码 
insert all 
into test_tb_grade3(USER_NAME,COURSE,SCORE) values(user_name, ‘语文’, CN_SCORE) 
into test_tb_grade3(USER_NAME,COURSE,SCORE) values(user_name, ‘数学’, MATH_SCORE) 
into test_tb_grade3(USER_NAME,COURSE,SCORE) values(user_name, ‘英语’, EN_SCORE) 
select user_name, CN_SCORE, MATH_SCORE, EN_SCORE from test_tb_grade2; 
commit; 

 别忘记commit操作,然后再查询TEST_TB_GRADE3,发现表中的数据就是列转成行了。

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/124752.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • c语言窗体关机程序代码,c语言 关机程序代码[通俗易懂]

    c语言窗体关机程序代码,c语言 关机程序代码[通俗易懂]通过C语言实现关机,有两种方式:1通过system函数,调用dos的关机命令。通过stdlib.h中的intsystem(char*cmd);可以执行dos命令cmd。dos下关机的命令为shutdown-s,于是嗲用system(“shutdown-s”);即可实现关机操作。2通过调用windows提供的api函数,来实现关机:voidshut_down_windows(){HAN…

    2022年7月22日
    11
  • pip的安装与卸载「建议收藏」

    前言我个人的理解是,pip是一种工具,可以帮助用户安装卸载一些需要的安装包,非常的简单实用,类似于yum下面介绍的是使用系统自带的python来安装pip。安装方法一sudoaptinstallpython-pip方法二wgethttps://bootstrap.pypa.io/get-pip.py#科学上网pythonget-pip.pypyth…

    2022年4月5日
    53
  • VLAN配置实例_ipsec配置步骤

    VLAN配置实例_ipsec配置步骤实验拓扑图实验要求:1.PC1和PC3所在接口为access;PVLANVLAN2PC2/4/5/6处于同一网段;其中PC2可以访问PC4/5/6;但PC4可以访问PC5,不能访问PC6;2.PC5不能访问PC6实验配置思路:1.PC2/4/5/6处于同一网段–DHCP下放IP地址PC1/3–使用路由器子接口DHCP下放IP地址2.为满足实验要求:将PC2划分到VLAN3、可以在同一VALN,也可以在不同VLAN,在这,我是把PC4/PC5都划分到VLAN4、PC6划分到VLAN5

    2022年9月19日
    0
  • pstack学习笔记

    pstack学习笔记################################################################################pstack学习笔记v0.12013.10.8*** 简介:pstack的功能是显示当前进程中函数的调用栈的关系,若是多线程的情况下,会显示各个      线程中函数调用的关系。 

    2022年9月14日
    0
  • stacktrace: java.lang.ClassCastException: java.util.HashMap cannot be cast to[通俗易懂]

    stacktrace: java.lang.ClassCastException: java.util.HashMap cannot be cast to[通俗易懂]今天线上发了好几封预警邮件,邮件内容如下:看了下项目报错的代码:ApiResult<WithdrawResultDto>withdrawResult=loanApiService.queryWithdrawResult(contractNo);WithdrawResultDtowithdraw=withdrawResult.getDa…

    2022年9月9日
    0
  • java抛出异常和捕获异常_java.lang.assertionerror

    java抛出异常和捕获异常_java.lang.assertionerror我有一个代码是围绕Web服务的Java包装程序,在例外情况下,它引发AxisFault异常(如下所示)org.apache.axis2.AxisFault:Policyenforcementfailedtoauthenticatetherequest.atorg.apache.axis2.util.Utils.getInboundFaultFromMessageContext(Ut…

    2022年9月12日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号