您的位置:首页 > 数据库

SQL行转列、列转行

2014-11-27 22:54 190 查看
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;

结果:



三、列转行
主要思路也是分组后使用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;
结果:



四、数据资料
1.http://www.cnblogs.com/lhj588/p/3315876.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: