设为首页收藏本站
查看: 115|回复: 0

[PHP] sql动态行转列

[复制链接]

论坛元老

Rank: 6Rank: 6

积分
34274
主题
17031
UID
1347
M币
67
贡献
17176

  • 发表于 2018-7-11 12:25:00 | 显示全部楼层 |阅读模式
    第一种方法: 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)
    ,美国空间,香港服务器,香港虚拟主机
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    在我站开通SVIP可同时获得17个站点VIP资源 立即登录 立即注册
    快速回复 返回顶部 返回列表