sql动态行转列的两种方法

时间:2024-01-24 07:17:41 

第一种方法:


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)

标签:sql,动态行,转列
0
投稿

猜你喜欢

  • tornado框架blog模块分析与使用

    2023-01-29 10:39:27
  • Python实现Tracert追踪TTL值的方法详解

    2023-06-24 13:08:14
  • python3 拼接字符串的7种方法

    2021-12-24 09:09:32
  • webpack-dev-server自动更新页面方法

    2024-04-19 09:48:10
  • Django学习笔记之ORM基础教程

    2022-07-25 22:59:07
  • Python实现html转换为pdf报告(生成pdf报告)功能示例

    2023-11-07 02:31:17
  • pandas按行按列遍历Dataframe的几种方式

    2023-07-04 15:36:05
  • mysql中general_log日志知识点介绍

    2024-01-12 23:49:58
  • appium测试之APP元素定位及基本工具介绍

    2021-09-24 20:51:47
  • jupyter notebook 多环境conda kernel配置方式

    2022-09-05 04:45:36
  • 浅谈python中的错误与异常

    2021-11-06 11:51:23
  • 利用Python编写个冷笑话生成器

    2021-05-10 15:13:20
  • 解析SQL Server 2008中的新语句:MERGE

    2009-01-13 13:57:00
  • 引起用户注意的界面方式

    2007-10-07 21:17:00
  • golang容易导致内存泄漏的6种情况汇总

    2024-04-25 13:20:17
  • python global关键字的用法详解

    2023-12-30 03:32:02
  • Keras保存模型并载入模型继续训练的实现

    2021-08-12 23:23:32
  • Python 实现键盘鼠标按键模拟

    2021-11-30 11:00:26
  • 浅谈音视频 pts dts基本概念及理解

    2023-11-13 03:31:26
  • python中readline判断文件读取结束的方法

    2022-12-14 06:22:51
  • asp之家 网络编程 m.aspxhome.com