sql多表行转列、级联行转列示例代码

前端之家收集整理的这篇文章主要介绍了sql多表行转列、级联行转列示例代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

现有两表A,B A表存储商品点击日志,B表存储商品 要求显示当天所有商品点击量列表并附带总数并按天排序
<div class="codetitle"><a style="CURSOR: pointer" data="85873" class="copybut" id="copybut85873" onclick="doCopy('code85873')"> 代码如下:

<div class="codebody" id="code85873">
declare @sql varchar(2000)
set @sql='select CONVERT(varchar(100),a.[Time],23) as 时间,count(b.title) as 总数'
select @sql =@sql+ ',sum(case b.title when '''+Title+''' then 1 else 0 end) as '+'['+Title+']'
from (select distinct title from B) as B
set @sql=@sql+' from A as a left join B as b on a.AId=B.Aid
group by CONVERT(varchar(100),23) order by CONVERT(varchar(100),23) desc'
exec(@sql)

显示结果

时间 总数 商品1 商品2 商品3
2013-11-11 5 1 0 4
2013-11-10 13 2 11 1

猜你在找的MsSQL相关文章