手机
当前位置:查字典教程网 >编程开发 >mssql数据库 >sql动态行转列的两种方法
sql动态行转列的两种方法
摘要:第一种方法:复制代码代码如下:select*from(selectUrl,casewhenMonth=01then'1月'whenMonth...

第一种方法:

复制代码 代码如下:

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动态行转列的两种方法】相关文章:

SQL2005Express中导入ACCESS数据库的两种方法

SqlServer 序号列的实现方法

mssql数据库系统崩溃后的一般处理步骤与方法

清除SQLServer日志的两种方法

SQL Server 不删除信息重新恢复自动编号列的序号的方法

跪求sql server2012行转列方案

安装sql server 2008时的4个常见错误和解决方法

SQL Server2005 异地备份的多种方法

sqlserver 2008手工修改表结构,表不能保存的问题与解决方法

sql中varchar和nvarchar的区别与使用方法

精品推荐
分类导航