• 技术文章 >数据库 >mysql教程

    sql动态行转列

    2016-06-07 17:44:07原创638

    第一种方法: select *from ( select Url,case when Month=01 then '1月' when Month=02 then '2月' when Month=03 then '3月' when Month=04 then '4月' when Month=05 then '5月' when Month=06 then '6月' when Month=07 then '7月' when Month=08 then '

    第一种方法:

    select *from ( select Url,case when Month=01 then '1月' when Month=02 then '2月' when Month=03 then '3月' when Month=04 then '4月' when Month=05 then '5月' when Month=06 then '6月' when Month=07 then '7月' when Month=08 then '8月' when Month=09 then '9月' when Month=10 then ' 10月' when Month=11 then '11月' when Month=12 then ' 12月'

    end month,Quality from (

    select Url,DATENAME(M,AuditingTime)Month,SUM(Quality) Quality from tb_order as a left join tb_WebSiteInfo as b on a.WebSiteInfoID=b.ID left join tb_OrderList as c on c.OrderID=a.ID where AuditingTime>'2013-01-01' and b.ID>0 and Auditing=2

    group by Url,DATENAME(M,AuditingTime) )as h ) as hh

    pivot ( sum(Quality) for month in([1月],[2月],[3月],[4月],[5月],[6月],[7月],[8月],[9月],[10月],[11月],[12月])) as a
    第二种方法:

    declare @sql varchar(8000)

    select @sql = isnull(@sql + ',' , '') + '['+CONVERT(varchar(7),AuditingTime,20)+']'

    from tb_order as a left join tb_WebSiteInfo as b on a.WebSiteInfoID=b.ID left join tb_OrderList as c on c.OrderID=a.ID where AuditingTime>'2013-01-01' and b.ID>0 and Auditing=2

    group by CONVERT(varchar(7),AuditingTime,20) print @sql declare @sql2 varchar(8000)='' set @sql2=' select *from (

    select Url, CONVERT(varchar(7),AuditingTime,20) AuditingTime,SUM(Quality) Quality from tb_order as a left join tb_WebSiteInfo as b on a.WebSiteInfoID=b.ID left join tb_OrderList as c on c.OrderID=a.ID where b.ID>0 and Auditing=2

    group by Url, CONVERT(varchar(7),AuditingTime,20)

    ) as hh pivot (sum(Quality) for AuditingTime in (' + @sql + ')) b'

    print @sql2

    exec(@sql2)

    ,美国空间,香港服务器,香港虚拟主机

    php入门到就业线上直播课:查看学习

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。

    千万级数据并发解决方案(理论+实战):点击学习

    Mysql单表千万级数据量的查询优化与性能分析

    Mysql主从原理及其在高并发系统中的应用

    专题推荐:动态 行转列
    上一篇:2年SQL Server DBA调优方面总结 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • ❤️‍🔥共22门课程,总价3725元,会员免费学• ❤️‍🔥接口自动化测试不想写代码?• 实例分析MySQL中pt-query-digest工具的使用记录• 简单聊聊MySQL中join查询• 深入理解MySQL索引优化器工作原理• MySQL子查询详细教程• MySQL关于Count函数的用法区别总结
    1/1

    PHP中文网