sql多表行转列、级联行转列示例代码
现有两表A,B
A表存储商品点击日志,B表存储商品
要求显示当天所有商品点击量列表并附带总数并按天排序
显示结果
A表存储商品点击日志,B表存储商品
要求显示当天所有商品点击量列表并附带总数并按天排序
代码如下:
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), a.[Time], 23) order by CONVERT(varchar(100), a.[Time], 23) desc' exec(@sql)
显示结果
时间 | 总数 | 商品1 | 商品2 | 商品3 |
2013-11-11 | 5 | 1 | 0 | 4 |
2013-11-10 | 13 | 2 | 11 | 1 |
相关推荐
云中舞步 2020-11-12
杨德龙 2020-11-11
JohnYork 2020-10-16
wangzhaotongalex 2020-09-22
xiaoseyihe 2020-11-16
不要皱眉 2020-10-14
Crazyshark 2020-11-13
K先生 2020-11-10
momode 2020-09-11
思君夜未眠 2020-09-04
点滴技术生活 2020-08-21
MaggieRose 2020-08-19
kevinweijc 2020-08-18
wintershii 2020-08-17
vapaad 2020-08-17
wera00 2020-08-17
移动开发与培训 2020-08-16
ReunionIsland 2020-08-16
JimyFengqi 2020-08-16