首页 > 代码库 > mysql 行转换为列
mysql 行转换为列
http://www.cnblogs.com/acelove/archive/2004/11/29/70434.html上提到了一个行列转换的方法,其实在2005里有更可读的写法,就是使用pivot运算符:
create table abc
(
student varchar(50),
class varchar(50),
grade int
)
INSERT INTO abc
SELECT ‘孙小美‘,‘数学‘,10 UNION ALL
SELECT ‘孙小美‘,‘语文‘,20 UNION ALL
SELECT ‘孙小美‘,‘英语‘,30 UNION ALL
SELECT ‘阿土伯‘,‘数学‘,40 UNION ALL
SELECT ‘阿土伯‘,‘语文‘,50 UNION ALL
SELECT ‘阿土伯‘,‘英语‘,60 UNION ALL
SELECT ‘小叮铛‘,‘数学‘,70 UNION ALL
SELECT ‘小叮铛‘,‘语文‘,80 UNION ALL
SELECT ‘小叮铛‘,‘英语‘,90
SELECT
student,
MAX(数学) AS 数学,
MAX(语文) AS 语文,
MAX(英语) AS 英语
FROM
(
SELECT
student,
CASE class WHEN ‘数学‘ THEN grade END AS 数学,
CASE class WHEN ‘语文‘ THEN grade END AS 语文,
CASE class WHEN ‘英语‘ THEN grade END AS 英语
FROM abc
) AS a
GROUP BY student
--用pivot运算符
select student,[数学] as ‘数学‘,[语文] as ‘语文‘ ,[英语] as ‘英语‘
from
(select * from abc) as source
pivot
(
sum(grade)
for class in
([数学],[语文],[英语])
) as p
(
student varchar(50),
class varchar(50),
grade int
)
INSERT INTO abc
SELECT ‘孙小美‘,‘数学‘,10 UNION ALL
SELECT ‘孙小美‘,‘语文‘,20 UNION ALL
SELECT ‘孙小美‘,‘英语‘,30 UNION ALL
SELECT ‘阿土伯‘,‘数学‘,40 UNION ALL
SELECT ‘阿土伯‘,‘语文‘,50 UNION ALL
SELECT ‘阿土伯‘,‘英语‘,60 UNION ALL
SELECT ‘小叮铛‘,‘数学‘,70 UNION ALL
SELECT ‘小叮铛‘,‘语文‘,80 UNION ALL
SELECT ‘小叮铛‘,‘英语‘,90
SELECT
student,
MAX(数学) AS 数学,
MAX(语文) AS 语文,
MAX(英语) AS 英语
FROM
(
SELECT
student,
CASE class WHEN ‘数学‘ THEN grade END AS 数学,
CASE class WHEN ‘语文‘ THEN grade END AS 语文,
CASE class WHEN ‘英语‘ THEN grade END AS 英语
FROM abc
) AS a
GROUP BY student
--用pivot运算符
select student,[数学] as ‘数学‘,[语文] as ‘语文‘ ,[英语] as ‘英语‘
from
(select * from abc) as source
pivot
(
sum(grade)
for class in
([数学],[语文],[英语])
) as p
不过对于不知道具体列名的程序还真不好解决,生成动态sql话(调用sp_executesql),臂如:
declare @sql varchar(8000)
set @sql = ‘select student,‘
select @sql = @sql + ‘sum(case class when ‘‘‘+class+‘‘‘then grade else 0 end) as ‘‘‘+class+‘‘‘,‘
from (select distinct class from abc) as a
select @sql = left(@sql,len(@sql)-1) + ‘ from abc group by student‘
exec(@sql)
set @sql = ‘select student,‘
select @sql = @sql + ‘sum(case class when ‘‘‘+class+‘‘‘then grade else 0 end) as ‘‘‘+class+‘‘‘,‘
from (select distinct class from abc) as a
select @sql = left(@sql,len(@sql)-1) + ‘ from abc group by student‘
exec(@sql)
倒是可以,不过却与当前存储过程调用不属于一批命令了,定义的CTE,局部临时表也访问不了,似乎只有放到业务层或数据层去解决了.
mysql 行转换为列
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。