您的位置:首页 > 博客中心 > 数据库 >

mysql 行转换为列

时间:2022-03-14 03:08

上提到了一个行列转换的方法,其实在2005里有更可读的写法,就是使用pivot运算符:

gxlsystem.com,布布扣create table abc 
gxlsystem.com,布布扣(
gxlsystem.com,布布扣student varchar(50),
gxlsystem.com,布布扣class varchar(50),
gxlsystem.com,布布扣grade int
gxlsystem.com,布布扣)
gxlsystem.com,布布扣INSERT INTO abc
gxlsystem.com,布布扣SELECT ‘孙小美‘,‘数学‘,10 UNION ALL
gxlsystem.com,布布扣SELECT ‘孙小美‘,‘语文‘,20 UNION ALL
gxlsystem.com,布布扣SELECT ‘孙小美‘,‘英语‘,30 UNION ALL
gxlsystem.com,布布扣SELECT ‘阿土伯‘,‘数学‘,40 UNION ALL
gxlsystem.com,布布扣SELECT ‘阿土伯‘,‘语文‘,50 UNION ALL
gxlsystem.com,布布扣SELECT ‘阿土伯‘,‘英语‘,60 UNION ALL
gxlsystem.com,布布扣SELECT ‘小叮铛‘,‘数学‘,70 UNION ALL
gxlsystem.com,布布扣SELECT ‘小叮铛‘,‘语文‘,80 UNION ALL
gxlsystem.com,布布扣SELECT ‘小叮铛‘,‘英语‘,90
gxlsystem.com,布布扣
gxlsystem.com,布布扣SELECT 
gxlsystem.com,布布扣    student,
gxlsystem.com,布布扣    MAX(数学) AS 数学,
gxlsystem.com,布布扣    MAX(语文) AS 语文,
gxlsystem.com,布布扣    MAX(英语) AS 英语
gxlsystem.com,布布扣FROM
gxlsystem.com,布布扣    (
gxlsystem.com,布布扣    SELECT 
gxlsystem.com,布布扣        student,
gxlsystem.com,布布扣        CASE class WHEN ‘数学‘ THEN grade END AS 数学,
gxlsystem.com,布布扣        CASE class WHEN ‘语文‘ THEN grade END AS 语文,
gxlsystem.com,布布扣        CASE class WHEN ‘英语‘ THEN grade END AS 英语
gxlsystem.com,布布扣    FROM abc
gxlsystem.com,布布扣    ) AS a
gxlsystem.com,布布扣GROUP BY student 
--用pivot运算符gxlsystem.com,布布扣
gxlsystem.com,布布扣select student,[数学] as ‘数学‘,[语文] as ‘语文‘ ,[英语] as ‘英语‘
gxlsystem.com,布布扣from
gxlsystem.com,布布扣 (select * from abc) as source
gxlsystem.com,布布扣    pivot
gxlsystem.com,布布扣    (
gxlsystem.com,布布扣        sum(grade)
gxlsystem.com,布布扣        for class  in
gxlsystem.com,布布扣        ([数学],[语文],[英语])
gxlsystem.com,布布扣    ) as p


不过对于不知道具体列名的程序还真不好解决,生成动态sql话(调用sp_executesql),臂如:

gxlsystem.com,布布扣declare @sql varchar(8000)
gxlsystem.com,布布扣set @sql = ‘select student,‘
gxlsystem.com,布布扣select @sql = @sql + ‘sum(case class when ‘‘‘+class+‘‘‘then grade else 0 end) as ‘‘‘+class+‘‘‘,‘
gxlsystem.com,布布扣  from (select distinct class from abc) as a 
gxlsystem.com,布布扣select @sql = left(@sql,len(@sql)-1) + ‘ from abc group by student‘
gxlsystem.com,布布扣exec(@sql)

倒是可以,不过却与当前存储过程调用不属于一批命令了,定义的CTE,局部临时表也访问不了,似乎只有放到业务层或数据层去解决了.

热门排行

今日推荐

热门手游