现在有这么一张表(https://img-ask.csdn.net/upload/201708/17/1502938958_357176.jpg)
如何用sql查询出这个效果(https://img-ask.csdn.net/upload/201708/17/1502938950_240666.jpg)
SELECT
stuName as 'name',
max(case stuCode when 's1001' then stuId else 0 end) as '1月' ,
max(case stuCode when 's1002' then stuId else 0 end) as '2月' ,
max(case stuCode when 's1003' then stuId else 0 end) as '3月' ,
max(case stuCode when 's1004' then stuId else 0 end) as '4月' ,
max(case stuCode when 's1005' then stuId else 0 end) as '5月' ,
max(case stuCode when 's1006' then stuId else 0 end) as '6月' ,
max(case stuCode when 's1007' then stuId else 0 end) as '7月' ,
max(case stuCode when 's1008' then stuId else 0 end) as '8月' ,
max(case stuCode when 's1009' then stuId else 0 end) as '9月' ,
max(case stuCode when 's1010' then stuId else 0 end) as '10月' ,
max(case stuCode when 's1011' then stuId else 0 end) as '11月' ,
max(case stuCode when 's1012' then stuId else 0 end) as '12月'
from stuInfo group by stuNnme order by stuNnme
这只是一个例子,具体的数据你就自己改就行了
饿 两张表贴反了 这个是原表
用sql转换成这样 人员id 先可以看成 这张图的人员
用一个行转列就可以转过来了啊
select userid group_concat( level order by month) from xxx group by userid;
_对,行转列就可以。level是评分,month 是月份,安装月份排序,得到每个userid 的每个月的评分,形成一条记录
最后结果基本上就是
user1, A,B,A,D
user2, A,C,C,D
这样的,不过,你要保证你每个user有12个月份的值,不然话,形成的列,就会变缺少值。
CREATE TABLE IF NOT EXISTS row_to_column
(people_id
varchar(50) DEFAULT NULL,month
int(11) DEFAULT NULL,score
varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO row_to_column
(people_id
, month
, score
) VALUES
('abcdefg', 1, 'A'),
('abcdefg', 2, 'B'),
('abcdefg', 3, 'A'),
('abcdefg', 4, 'C'),
('abcdefg', 5, 'B'),
('abcdefg', 6, 'B'),
('abcdefg', 7, 'A'),
('abcdefg', 8, 'A');
select people_id,
max(case month when 1 then score else '' end) 1月份,
max(case month when 2 then score else '' end) 2月份,
max(case month when 3 then score else '' end) 3月份,
max(case month when 4 then score else '' end) 4月份,
max(case month when 5 then score else '' end) 5月份,
max(case month when 6 then score else '' end) 6月份,
max(case month when 7 then score else '' end) 7月份,
max(case month when 8 then score else '' end) 8月份,
max(case month when 9 then score else '' end) 9月份,
max(case month when 10 then score else '' end) 10月份,
max(case month when 11 then score else '' end) 11月份,
max(case month when 12 then score else '' end) 12月份
from row_to_column
group by people_id
order by people_id;
http://www.cnblogs.com/cpcpc/archive/2013/04/08/3009021.html